选中WPF Datagrid复选框列

时间:2018-01-15 16:19:15

标签: c# wpf checkbox datagrid

我的datagrid复选框列:

                    <DataGridTemplateColumn MaxWidth="45">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <CheckBox x:Name="check_tutar"  VerticalAlignment="Center" HorizontalAlignment="Center" HorizontalContentAlignment="Center" Checked="check_tutar_Checked"></CheckBox>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>

我想访问此复选框并更改已检查的属性。我尝试使用defalut方法:check_tutar.IsChecked = false;

但没有用,因为我无法使用名称访问该复选框。如何更改datagrid列复选框选中的属性?

1 个答案:

答案 0 :(得分:2)

您应该将IsChecked的{​​{1}}属性绑定到数据对象的CheckBox属性并设置此属性,而不是尝试访问bool控件本身:

CheckBox

数据类应该实现<DataGridTemplateColumn.CellTemplate> <DataTemplate> <CheckBox x:Name="check_tutar" IsChecked="{Binding IsChecked, UpdateSourceTrigger=PropertyChanged}" /> </DataTemplate> </DataGridTemplateColumn.CellTemplate> 接口并在设置INotifyPropertyChanged属性时提出更改通知:

IsChecked

然后,您可以通过设置相应对象的public class YourClass : INotifyPropertyChanged { private bool _isChecked; public bool IsChecked { get { return _isChecked; } set { _isChecked = value; NotifyPropertyChanged(); } } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged([CallerMemberName] String propertyName = "") { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } 属性来简单地选中/取消选中CheckBoxDataGrid行的IsChecked,例如:

List<YourClass> theItems = new List<YourClass>(0) { ... };
dataGrid1.ItemsSource = theItems;

//check the first row:
theItems[0].IsChecked = true;

这基本上是WPF和DataGrid的工作原理。

相关问题