最近的一个项目是用MVVM实现,在实现功能的时候,就会有一些东西,和以前有很大的区别,项目中就用到了常用的序号,就是在Datagrid里的一个字段,用checkbox来实现。

既然是MVVM,就要用到ModleView,View和Model三层。

先看一下效果

当然,也可以确定是哪一项被选中了,这个代码里有。

实现这个全选功能,用到了三个DLL文件,分别为GalaSoft.MvvmLight.Extras.WPF4.dll,GalaSoft.MvvmLight.WPF4.dll,System.Windows.Interactivity.dll

Model曾需要实现INotifyPropertyChanged接口,以方便向客户端通知属性被更改了

  1. public class MainModel:INotifyPropertyChanged
  2. {
  3. public event PropertyChangedEventHandler PropertyChanged;
  4.  
  5. private void INotifyPropertyChanged(string name)
  6. {
  7. if (PropertyChanged != null)
  8. {
  9. PropertyChanged(this, new PropertyChangedEventArgs(name));
  10. }
  11. }
  12.  
  13. private int xh;
  14.  
  15. public int Xh
  16. {
  17. get { return xh; }
  18. set { xh = value; }
  19. }
  20.  
  21. private string name;
  22.  
  23. public string Name
  24. {
  25. get { return name; }
  26. set { name = value;
  27. INotifyPropertyChanged("Name");
  28. }
  29. }
  30.  
  31. private int age;
  32.  
  33. public int Age
  34. {
  35. get { return age; }
  36. set { age = value;
  37. INotifyPropertyChanged("Age");
  38. }
  39. }
  40.  
  41. private bool isSelected;
  42.  
  43. public bool IsSelected
  44. {
  45. get { return isSelected; }
  46. set { isSelected = value;
  47. INotifyPropertyChanged("IsSelected");
  48. }
  49. }
  50. }

Model

Model层里除了Datagrid里显示的序号,姓名和年龄意外,还有一个就是IsSelected,是用来确定是否选中的。

ViewModel层继承ViewModelBase,它来自GalaSoft.MvvmLight命名空间,重点是用到了里面的RaisePropertyChanged

全选的checkbox和下面选中的checkbox是分开来写的,各自有各自的Command,选中和不选中都有,IsSelectAll是用来标识是不是全选中

  1. public class MainViewModel : ViewModelBase
  2. {
  3. public MainViewModel()
  4. {
  5. DataGridBaseInfo = AddDataGridInfo();
  6. }
  7. /// <summary>
  8. /// 给Datagrid绑定的属性
  9. /// </summary>
  10. private List<MainModel> dataGridBaseInfo;
  11.  
  12. public List<MainModel> DataGridBaseInfo
  13. {
  14. get { return dataGridBaseInfo; }
  15. set
  16. {
  17. dataGridBaseInfo = value;
  18. RaisePropertyChanged("DataGridBaseInfo");
  19. }
  20. }
  21. /// <summary>
  22. /// 显示按钮
  23. /// </summary>
  24. private RelayCommand buttonCommand;
  25.  
  26. public RelayCommand ButtonCommand
  27. {
  28. get
  29. {
  30. return buttonCommand ?? (buttonCommand = new RelayCommand(
  31. () =>
  32. {
  33. int count = DataGridBaseInfo.ToList().FindAll(p => p.IsSelected == true).Count;
  34. MessageBox.Show("选中了" + count + "项");
  35. //for (int i = 0; i < count; i++)
  36. // MessageBox.Show(DataGridBaseInfo.ToList().FindAll(p=>p.IsSelected==true)[i].Name + "," + DataGridBaseInfo.ToList().FindAll(p=>p.IsSelected==true)[i].Age);
  37. }));
  38. }
  39. }
  40.  
  41. public List<MainModel> AddDataGridInfo()
  42. {
  43. MainModel model;
  44. List<MainModel> list = new List<MainModel>();
  45. for (int i = ; i < ; i++)
  46. {
  47. model = new MainModel();
  48. model.Xh = i;
  49. model.Name = "李雷" + i;
  50. model.Age = + i;
  51. list.Add(model);
  52. }
  53. return list;
  54. }
  55. /// <summary>
  56. /// 选中
  57. /// </summary>
  58. private RelayCommand selectCommand;
  59.  
  60. public RelayCommand SelectCommand
  61. {
  62. get
  63. {
  64. return selectCommand ?? (selectCommand = new RelayCommand(
  65. () =>
  66. {
  67. int selectCount = DataGridBaseInfo.ToList().Count(p => p.IsSelected == false);
  68. if (selectCount.Equals())
  69. {
  70. IsSelectAll = true;
  71. }
  72. }));
  73. }
  74. }
  75. /// <summary>
  76. /// 取消选中
  77. /// </summary>
  78. private RelayCommand unSelectCommand;
  79.  
  80. public RelayCommand UnSelectCommand
  81. {
  82. get
  83. {
  84. return unSelectCommand ?? (unSelectCommand = new RelayCommand(
  85. () =>
  86. {
  87. IsSelectAll = false;
  88. }));
  89. }
  90. }
  91.  
  92. private bool isSelectAll = false;
  93.  
  94. public bool IsSelectAll
  95. {
  96. get { return isSelectAll; }
  97. set
  98. {
  99. isSelectAll = value;
  100. RaisePropertyChanged("IsSelectAll");
  101. }
  102. }
  103.  
  104. /// <summary>
  105. /// 选中全部
  106. /// </summary>
  107. private RelayCommand selectAllCommand;
  108.  
  109. public RelayCommand SelectAllCommand
  110. {
  111. get
  112. {
  113. return selectAllCommand ?? (selectAllCommand = new RelayCommand(ExecuteSelectAllCommand, CanExecuteSelectAllCommand));
  114. }
  115. }
  116.  
  117. private void ExecuteSelectAllCommand()
  118. {
  119. if (DataGridBaseInfo.Count < ) return;
  120. DataGridBaseInfo.ToList().FindAll(p => p.IsSelected = true);
  121. }
  122.  
  123. private bool CanExecuteSelectAllCommand()
  124. {
  125. if (DataGridBaseInfo != null)
  126. {
  127. return DataGridBaseInfo.Count > ;
  128. }
  129. else
  130. return false;
  131. }
  132.  
  133. /// <summary>
  134. /// 取消全部选中
  135. /// </summary>
  136. private RelayCommand unSelectAllCommand;
  137.  
  138. public RelayCommand UnSelectAllCommand
  139. {
  140. get { return unSelectAllCommand ?? (unSelectAllCommand = new RelayCommand(ExecuteUnSelectAllCommand, CanExecuteUnSelectAllCommand)); }
  141. }
  142.  
  143. private void ExecuteUnSelectAllCommand()
  144. {
  145. if (DataGridBaseInfo.Count < )
  146. return;
  147. if (DataGridBaseInfo.ToList().FindAll(p => p.IsSelected == false).Count != )
  148. IsSelectAll = false;
  149. else
  150. DataGridBaseInfo.ToList().FindAll(p => p.IsSelected = false);
  151. }
  152.  
  153. private bool CanExecuteUnSelectAllCommand()
  154. {
  155. if (DataGridBaseInfo != null)
  156. {
  157. return DataGridBaseInfo.Count > ;
  158. }
  159. else
  160. {
  161. return false;
  162. }
  163. }
  164. }

ViewModel

View层需要 xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" ,xmlns:Custom="http://www.galasoft.ch/mvvmlight" 两个命名空间

由于序号是绑定过来的,因此是用了stackpanel把checkbox和label放到了一起

  1. <Grid>
  2. <Grid.RowDefinitions>
  3. <RowDefinition Height="20"/>
  4. <RowDefinition Height="*"/>
  5. <RowDefinition Height="20"/>
  6. </Grid.RowDefinitions>
  7. <DataGrid Grid.Row="1" ItemsSource="{Binding DataGridBaseInfo, Mode=TwoWay}" Margin="10" AutoGenerateColumns="False">
  8. <DataGrid.Columns>
  9. <DataGridTemplateColumn>
  10. <DataGridTemplateColumn.Header>
  11. <CheckBox Content="全选" IsChecked="{Binding IsSelectAll,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
  12. <i:Interaction.Triggers>
  13. <i:EventTrigger EventName="Checked">
  14. <Custom:EventToCommand Command="{Binding DataContext.SelectAllCommand, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" CommandParameter="{Binding IsSelectAll, ElementName=qx}"/>
  15. </i:EventTrigger>
  16. <i:EventTrigger EventName="Unchecked">
  17. <Custom:EventToCommand Command="{Binding DataContext.UnSelectAllCommand, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" CommandParameter="{Binding IsSelectAll, ElementName=qx}"/>
  18. </i:EventTrigger>
  19. </i:Interaction.Triggers>
  20. </CheckBox>
  21. </DataGridTemplateColumn.Header>
  22. <DataGridTemplateColumn.CellTemplate>
  23. <DataTemplate>
  24. <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
  25. <CheckBox x:Name="cbXh" VerticalAlignment="Center" IsChecked="{Binding IsSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
  26. <i:Interaction.Triggers>
  27. <i:EventTrigger EventName="Checked">
  28. <Custom:EventToCommand Command="{Binding DataContext.SelectCommand, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" CommandParameter="{Binding IsChecked, ElementName=cbXh}"/>
  29. </i:EventTrigger>
  30. <i:EventTrigger EventName="Unchecked">
  31. <Custom:EventToCommand Command="{Binding DataContext.UnSelectCommand, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" CommandParameter="{Binding IsChecked, ElementName=cbXh}"/>
  32. </i:EventTrigger>
  33. </i:Interaction.Triggers>
  34. </CheckBox>
  35. <Label Content="{Binding Xh}" FontSize="14"/>
  36. </StackPanel>
  37. </DataTemplate>
  38. </DataGridTemplateColumn.CellTemplate>
  39. </DataGridTemplateColumn>
  40. <DataGridTextColumn Header="姓名" Binding="{Binding Name}" Width="*"/>
  41. <DataGridTextColumn Header="年龄" Binding="{Binding Age}" Width="*"/>
  42. </DataGrid.Columns>
  43. </DataGrid>
  44. <Button Content="显示" Grid.Row="2" Width="50" Command="{Binding ButtonCommand}"/>
  45. </Grid>

View

当时实现这个功能的时候也花了不少时间,希望给需要的人一点帮助。

代码

MVVM框架下,WPF实现Datagrid里的全选和选择的更多相关文章

  1. MVVM框架下 WPF隐藏DataGrid一列

    最近的一个项目,需要在部分用户登录的时候,隐藏DataGrid中的一列,但是常规的绑定不好使,在下面举个例子. XAML部分代码 <Window x:Class="DataGridCo ...

  2. MVVM框架从WPF移植到UWP遇到的问题和解决方法

    MVVM框架从WPF移植到UWP遇到的问题和解决方法 0x00 起因 这几天开始学习UWP了,之前有WPF经验,所以总体感觉还可以,看了一些基础概念和主题,写了几个测试程序,突然想起来了前一段时间在W ...

  3. MVVM模式下WPF动态绑定展示图片

    MVVM模式下WPF动态展示图片,界面选择图标,复制到项目中固定目录下面,保存到数据库的是相对路径,再次读取的时候是根据数据库的相对路径去获取项目中绝对路径的图片展示. 首先在ViewModel中 / ...

  4. easyui datagrid里的复选框置灰方法

    easyui datagrid里的复选框置灰方法: $('.datagrid input').prop('disabled',true);//复选框置灰

  5. wpf DataGrid CheckBox列全选

    最近在wpf项目中遇到当DataGrid的header中的checkbox选中,让该列的checkbox全选问题,为了不让程序员写自己的一堆事件,现写了一个自己的自定义控件 在DataGrid的 &l ...

  6. WPF MVVM框架下,VM界面写控件

    MVVM正常就是在View页面写样式,ViewModel页面写逻辑,但是有的时候纯在View页面写样式并不能满足需求.我最近的这个项目就遇到了,因此只能在VM页面去写样式控件,然后绑定到View页面. ...

  7. 关于使用MVVM模式在WPF的DataGrid控件中实现ComboBox编辑列

    最近在做一个组态软件的项目,有一个需求需要在建立IO设备变量的时候选择变量的类型等. 建立IO变量的界面是一个DataGrid实现的,可以一行一行的新建变量,如下如所示: 这里需要使用带有ComboB ...

  8. mvvm框架下页面与ViewModel的各种参数传递方式

    传单个参数的话在xaml用     Command={Binding ViewModel的事件处理名称}    CommandParameter={Binding 要传递的控件名称} ViewMode ...

  9. 【WPF】一组CheckBox的全选/全不选功能

    需求:给一组CheckBox做一个全选/全不选的按钮. 思路:CheckBox不像RadioButton那样拥有GroupName属性来分组,于是我想的方法是将这组CheckBox放到一个布局容器中, ...

随机推荐

  1. C# asp.net 搭建微信公众平台(可实现关注消息与消息自动回复)的代码以及我所遇到的问题

    [引言] 利用asp.net搭建微信公众平台的案例并不多,微信官方给的案例是用PHP的,网上能找到的代码很多也是存在着这样那样的问题或者缺少部分方法,无法使用,下面是我依照官方文档写的基于.net 搭 ...

  2. 总结js的一些复制方法

    1.复制对象: var item1={XXX}; var item2=$.extend(true,{},item1);//深度克隆对象(jQuery方法). lodash也有相关方法:https:// ...

  3. js实现输入框数量加减【转】

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  4. postman发送带cookie的http请求

    1:需求:测试接口的访问权限,对于某些接口A可以访问,B不能访问. 2:问题:对于get请求很简单,登录之后,直接使用浏览器访问就可以: 对于post请求的怎么测试呢?前提是需要登录态,才能访问接口. ...

  5. bootstrap内置网格式布局系统:

    bootstrap分为12栏,若想要一个元素占用一定的栏数的宽度,可以在这个元素上用一个特定的类,就比如说span1.span2....类. 定义的布局: 定义page-header类,在这个类当中为 ...

  6. PHP 小数点保留两位【转】

    最近在做统计这一块内容,接触关于数字的数据比较多, 用到了三个函数来是 数字保留小数后 N 位: 接下来简单的介绍一下三个函数: 1.number_format echo number_format( ...

  7. 开启PHP的伪静态

    1.检测Apache是否支持mod_rewrite 通过php提供的phpinfo()函数查看环境配置,通过Ctrl+F查找到“Loaded Modules”,其中列出了所有 apache2handl ...

  8. java反射技术详解

    反射: 其实就是动态的从内存加载一个指定的类,并获取该类中的所有的内容. 反射的好处:大大的增强了程序的扩展性. 反射的基本步骤: 1. 获得Class对象,就是获取到指定的名称的字节码文件对象. 2 ...

  9. 无参数实例化Configuration对象以及addResource无法加载core-site.xml中的内容

    core-site.xml中配置的fs.default.name是hdfs://localhost:9000.但是这里读取出来的是本地文件系统.原因暂不知?有谁知道?

  10. 数据库之SQL编程

    定义局部变量 declare @num int 途径一: 途径二: set 和select赋值方式的区别 唯一区别,如果从数据库表中获取数据,只能用 select ) select @name =st ...