项目中用到DataGrid, 需要在第一列添加checkbox, 可以多选、全选。
其中涉及的概念DataTemplate, DataGridCellStyle, DataGridCellControlTemplate,Binding, OnPropertyChanged等。
有下面是实现思路:
1.继承INotifyPropertyChanged接口,实现OnPropertyChanged方法:
public abstract class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Raises this object's PropertyChanged event.
/// </summary>
/// <param name="propertyName">The property that has a new value</param>
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
//..................
}
2. 实现viewModel, 添加IsSelected属性, 存储当前多选状态
private bool _isSelected = true;
public bool IsSelected
{
get { return _isSelected; }
set
{
_isSelected = value;
OnPropertyChanged("IsSelected");
}
}
3.在VM/Model准备好后, 我们接下来开始对DataGrid进行style自定义
4.准备checkbox的DataTemplate:
<DataTemplate x:Key="CheckboxDataTemplate1">
<Grid>
<CheckBox x:Name="_chkSelected"
Height="16"
HorizontalAlignment="Center"
VerticalAlignment&