项目中用到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="Center"
                        Background="{x:Null}"
                        VerticalContentAlignment="Center"
                        HorizontalContentAlignment="Center"
                        Click="_chkSelected_OnClick"
                        IsThreeState="False"
                        IsChecked="{Binding IsSelected, Mode=OneWay, FallbackValue=True}"
                        />
          </Grid>
        </DataTemplate>
此示例中checkbox只有简单的2种状态,
1)IsChecked属性绑定VM的IsSelected属性;
2)Mode为OneWay是因为我们需求是用户可以多选行然后点击某行头选中多行。此功能在Click事件中遍历当前所有选中的行,然后更改其VM的IsSelected属性。因此不需要TwoWay模式;
3)在Binding中添加了FallbackValue, 此属性指示当binding失败时给出的默认值。此例中因为DataTemplate也应用在列头, 而列头的DataContext和DataGridRow不同;
4)在Click事件处理函数中,判断当前点击的列头还是行头, 更改对应DataContext的IsSelected属性。 如:
      private void _chkSelected_OnClick(object sender, RoutedEventArgs e)
        {
            CheckBox chkSelected = e.OriginalSource as CheckBox;
            if (null == chkSelected)
            {
                return;
            }
            var studyModel = chkSelected.DataContext as StudyModel;
            bool isChecked = chkSelected.IsChecked.HasValue ? chkSelected.IsChecked.Value : true;
            FrameworkElement templateParent = chkSelected.TemplatedParent is FrameworkElement
                                                  ? (chkSelected.TemplatedParent as FrameworkElement).TemplatedParent as FrameworkElement
                                                  : null;
            if (templateParent is DataGridColumnHeader)
            {
                MainViewModel mvm = this.DataContext as MainViewModel;
                if (null != mvm)
                {
                    foreach (var sm in mvm.StudyList)
                    {
                        sm.IsSelected = isChecked;
                    }
                }
            }
            else if (templateParent is DataGridCell)
            {
                if (null != studyModel && null != this._grdStudyList.SelectedItems && this._grdStudyList.SelectedItems.Contains(studyModel))
                {
                    foreach (var otherSelected in this._grdStudyList.SelectedItems.OfType<StudyModel>())
                    {
                        otherSelected.IsSelected = isChecked;
                    }
                }
            }
        }
     其中MainViewModel为主VM, 其包含一个ObservableCollection<StudyModel> StudyList, 而StudyModel包含IsSelected属性, 二者都实现OnpropertyChanged方法; _grdStudyList为xaml中的DataGrid
5.应用DataTemplate到DataGridColumnHeader和DataGridCell, 如:
      <Style x:Key="DataGridCheckboxColumnHeaderStyle1" TargetType="{x:Type DataGridColumnHeader}">
            <Setter Property="ContentTemplate" Value="{DynamicResource CheckboxDataTemplate1}"/>
            <Setter Property="HorizontalAlignment" Value="Stretch"/>
            <Setter Property="VerticalAlignment" Value="Stretch"/>
      </Style>
      <Style x:Key="DataGridCheckboxCellStyle1" TargetType="{x:Type DataGridCell}">      
        <Setter Property="Padding" Value="20,0"/>                
        <Setter Property="ContentTemplate" Value="{DynamicResource CheckboxDataTemplate1}"/>     
        <Setter Property="Background" Value="#FFC1C1C1"/>        
        <Setter Property="BorderBrush" Value="{x:Null}"/>              
        <Setter Property="BorderThickness" Value="0"/>               
        <Setter Property="Template" Value="{DynamicResource DataGridCheckboxCellControlTemplate1}"/>      
        <Style.Triggers>                         
              <Trigger Property="IsSelected" Value="True">                              
                    <Setter Property="Background" Value="#FFC1C1C1"/>                       
                    <Setter Property="BorderBrush" Value="{x:Null}"/>                  
              </Trigger>           
        </Style.Triggers>           
       </Style>                    
       <ControlTemplate x:Key="DataGridCheckboxCellControlTemplate1" TargetType="{x:Type DataGridCell}">        
          <Border
                  BorderBrush="{TemplateBinding BorderBrush}"
                  BorderThickness="{TemplateBinding BorderThickness}"
                  Background="{TemplateBinding Background}"
                  SnapsToDevicePixels="True">                    
                <ContentPresenter 
                      ContentTemplate="{TemplateBinding ContentTemplate}"
                      Content="{TemplateBinding Content}"
                      ContentStringFormat="{TemplateBinding ContentStringFormat}"
                      SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>                
          </Border>
       </ControlTemplate>
6.应用CellStyle和HeaderStyle到DataGrid:
      <DataGrid
                x:Name="_grdStudyList"
ItemsSource="{Binding StudyList}"
AutoGenerateColumns="False"
FrozenColumnCount="1" Background="#FF999797">
          <DataGrid.Columns>                   
             <DataGridCheckBoxColumn 
                        x:Name="_dtcSelected"
Header=""
HeaderStyle="{StaticResource DataGridCheckboxColumnHeaderStyle1}"
CellStyle="{StaticResource DataGridCheckboxCellStyle1}"
MinWidth="60" CanUserReorder="False" MaxWidth="60"/>

wpf中为DataGrid添加checkbox支持多选全选的更多相关文章

  1. DataTable添加checkbox实现表格数据全选,单选(点选)

    Datatables是一款jquery表格插件.它是一个高度灵活的工具,可以将任何HTML表格添加高级的交互功能. 分页,即时搜索和排序 几乎支持任何数据源:DOM, javascript, Ajax ...

  2. WPF 中获取DataGrid 模板列中控件的对像

    WPF 中获取DataGrid 模板列中控件的对像 #region 当前选定行的TextBox获得焦点 /// <summary> /// 当前选定行的TextBox获得焦点 /// &l ...

  3. wpf中的datagrid绑定操作按钮是否显示或者隐藏

    如图,需要在wpf中的datagrid的操作那列有个确认按钮,然后在某些条件下确认按钮可见,某些情况下不可见的,放在mvc里直接在cshtml页面中if..else就行了. 但是在wpf里不行..网上 ...

  4. DEV控件中GridView中的复选框与CheckBox实现联动的全选功能

    最初的界面图如图1-1(全选框ID: cb_checkall  DEV控件名称:gcCon ): 要实现的功能如下图(1-2  1-3  1-4)及代码所示: 图1-2 图1-3 图1-4 O(∩_∩ ...

  5. Android开发CheckBox控件,全选,反选,取消全选

    在Android开发中我们经常会使用CheckBox控件,那么怎么实现CheckBox控件的全选,反选呢 首先布局我们的界面: <?xml version="1.0" enc ...

  6. WPF中嵌入Office编辑器(支持Word、Excel、PPT、Visio等)

    现在有一个项目,需要使用wpf做一个简单的客户端,用来生成word.excel.ppt.visio等文档,这就需要能够在wpf中嵌入office的编辑器,并对office文档进行编辑. 在网上搜索了一 ...

  7. Winform开发 如何为dataGridView 添加CheckBox列,并获取选中行

    //添加CheckBox列 DataGridViewCheckBoxColumn columncb = new DataGridViewCheckBoxColumn(); columncb.Heade ...

  8. CheckBox获取一组及全选

    获取一组CheckBox: jQuery: $(function () { $("input[name=names]").click(function () { //获得所有的na ...

  9. checkbox实现单选,全选,反选,取消选

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools=&q ...

随机推荐

  1. busybox rmmod error — rmmod: chdir(2.6.25): No such file or directory

    busybox rmmod error rmmod: chdir(2.6.25): No such file or directory 1. install your modules in dir / ...

  2. [SCOI2013]火柴棍数字(背包)

    题目 做饭 由于越高位越好,我们先得出能组成的最高位 \(f[i][j][k]\)表示从低到高位第\(i\)位,手里拿着\(j\)根火柴,第\(i\)位是否为\(0\)所需要的最少火柴 我们转移仅需得 ...

  3. Windos Server 2008 Tomcat 安装

    web服务:apache-tomcat-7.0.75环境:jdk-7u80-windows-i586 1.安装jdk环境包 2.配置环境变量--> 环境变量--> 新建W --> 变 ...

  4. 主攻ASP.NET MVC4.0之重生:Jquery Mobile 表单元素

    相关代码: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <tit ...

  5. gem Errno::ECONNRESET: Connection reset by peer - SSL_connect

    问题描述 在使用gem安装软件包时,会时常遇到下面的问题: ERROR: While executing gem ... (Gem::RemoteFetcher::FetchError) Errno: ...

  6. 八、golang文本操作、json协议

    一.终端读写 操作终端相关文件语句常量,go所有的都是接口 os.Stdin:标准输入 os.Stdout:标准输入,只要实现输出这个接口,打印到终端, os.Stderr:标准错误输出 os.Ope ...

  7. debian内核代码执行流程(三)

    接续<debian内核代码执行流程(二)>未完成部分 下面这行输出信息是启动udevd进程产生的输出信息: [ ]: starting version 175是udevd的版本号. 根据& ...

  8. iOS下的WiFi开发

    iOS下Wi-Fi开发需要添加依赖库SystemConfiguration.framework,在需要使用Wi-Fi信息的控制器下引入头文件#import <SystemConfiguratio ...

  9. gitLab 傻瓜式使用教程

    第一步,先去gitLab网上注册一下gitLab 进网站注册出来是这个界面: 2016082993103QQ20160829-1.png 然后进行人机验证(这个没啥困难的0.0) 2016082998 ...

  10. shell中嵌套执行expect命令实例(利用expect实现自动登录)

    expect是 #!/bin/bashpasswd='123456'/usr/bin/expect <<EOFset time 30spawn ssh root@192.168.76.10 ...