最近的一个项目是用MVVM实现,在实现功能的时候,就会有一些东西,和以前有很大的区别,项目中就用到了常用的序号,就是在Datagrid里的一个字段,用checkbox来实现。
既然是MVVM,就要用到ModleView,View和Model三层。
先看一下效果
当然,也可以确定是哪一项被选中了,这个代码里有。
实现这个全选功能,用到了三个DLL文件,分别为GalaSoft.MvvmLight.Extras.WPF4.dll,GalaSoft.MvvmLight.WPF4.dll,System.Windows.Interactivity.dll
Model曾需要实现INotifyPropertyChanged接口,以方便向客户端通知属性被更改了
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
public class MainModel:INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private void INotifyPropertyChanged(string name) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(name)); } } private int xh; public int Xh { get { return xh; } set { xh = value; } } private string name; public string Name { get { return name; } set { name = value; INotifyPropertyChanged("Name"); } } private int age; public int Age { get { return age; } set { age = value; INotifyPropertyChanged("Age"); } } private bool isSelected; public bool IsSelected { get { return isSelected; } set { isSelected = value; INotifyPropertyChanged("IsSelected"); } } }
Model层里除了Datagrid里显示的序号,姓名和年龄意外,还有一个就是IsSelected,是用来确定是否选中的。
ViewModel层继承ViewModelBase,它来自GalaSoft.MvvmLight命名空间,重点是用到了里面的RaisePropertyChanged
全选的checkbox和下面选中的checkbox是分开来写的,各自有各自的Command,选中和不选中都有,IsSelectAll是用来标识是不是全选中
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
public class MainViewModel : ViewModelBase { public MainViewModel() { DataGridBaseInfo = AddDataGridInfo(); } /// <summary> /// 给Datagrid绑定的属性 /// </summary> private List<MainModel> dataGridBaseInfo;