我的数据网格复选框列:
<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;
但不起作用,因为我不能使用名称访问复选框。如何更改数据格列复选框选中属性?
发布于 2018-01-16 00:30:46
您应该将CheckBox的IsChecked属性绑定到数据对象的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));
}
}然后,您可以通过设置相应对象的CheckBox属性,简单地选中/取消选中DataGrid中行的IsChecked,例如:
List<YourClass> theItems = new List<YourClass>(0) { ... };
dataGrid1.ItemsSource = theItems;
//check the first row:
theItems[0].IsChecked = true;这基本上就是WPF和DataGrid的工作方式。
https://stackoverflow.com/questions/48266868
复制相似问题