Dot-Net

DataGrid 創建 RadioButton 列

  • April 4, 2012

我有綁定到 DataGrid 的對象。我創建了一個綁定到對象的 Is Default 屬性的單選按鈕列。

當應用程序啟動時,正確的項目顯示為預設值,但是綁定永遠不會更新。我想要的行為是讓使用者選中一個單選框並將該對像變為預設值。

       <DataGrid CanUserAddRows="False" AutoGenerateColumns="False" Name="TEst" >
       <DataGrid.Columns >
           <DataGridTextColumn Header="Value" Binding="{Binding Path=Name, Mode=OneTime}"/>

           <DataGridTemplateColumn Header="Is Default">
               <DataGridTemplateColumn.CellTemplate>
                   <DataTemplate>
                       <RadioButton GroupName="Test" IsChecked="{Binding IsDefault}" />
                   </DataTemplate>
               </DataGridTemplateColumn.CellTemplate>
           </DataGridTemplateColumn>

       </DataGrid.Columns>
   </DataGrid>

private class Test : INotifyPropertyChanged
   {
       public string Name
       {
           get;
           set;
       }
       bool isDefult;
       public bool IsDefault
       {
           get
           {
               return isDefult;
           }
           set
           {
               isDefult = value;
           }
       }

       public event PropertyChangedEventHandler PropertyChanged;
   }

   public MainWindow()
   {
       this.InitializeComponent();
       Test[] ya = new Test[] { new Test { Name = "1", IsDefault = false }, new Test { Name = "2", IsDefault = false }, new Test { Name = "3", IsDefault = true } };

       this.TEst.ItemsSource = ya;
   }

我整個下午都在拉頭髮。任何幫助都會受到喜愛。

這很奇怪,但您所要做的就是更改 RadioButton 的綁定:

<RadioButton GroupName="Test" IsChecked="{Binding IsDefault, UpdateSourceTrigger=PropertyChanged}" />

據我所知,預設值是LostFocus,但是DataGrid裡面的focus有一些問題。我不知道為什麼會出現問題。

還有一個問題:在屬性PropertyChanged的 setter 中引發事件。IsDefault現在一切正常,無需通知,但如果您添加更多 xaml 程式碼,將很難找出 UI 未更新的原因。

引用自:https://stackoverflow.com/questions/5422820