项目中用到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. qt_hal_verion

    /opt/EmbedSky/B2/linux-3.0.35/drivers/mxc/gpu-viv/hal/kernel/inc/gc_hal_version.h 文件中的具体版本 export DI ...

  2. EG:nginx反向代理两台web服务器,实现负载均衡 所有的web服务共享一台nfs的存储

    step1: 三台web服务器环境配置:iptables -F; setenforce 0 关闭防火墙:关闭setlinux step2:三台web服务器 装软件 step3: 主机修改配置文件:vi ...

  3. Linux静默安装weblogic

    本实验安装weblogic10系列版本 #创建weblogic用户组. [root@admin /]# groupadd weblogic[root@admin /]# useradd -g webl ...

  4. complexHeatmap包画分类热图

    用途:一般我们画热图是以连续变量作为填充因子,complexHeatmap的oncopoint函数可以以类别变量作为填充因子作热图. 用法:oncoPrint(mat, get_type = func ...

  5. php数组函数-array_reduce()

    array_reduce()函数发送数组中的值到用户自定义函数,并返回一个字符串. 注:如果数组是空的或则初始化值未传递,该函数返回NULL array_reduce(array,myfunction ...

  6. ubuntu centos macos 配置上网代理

    因为我国强大的GFW,导致很多国外的应用无法安装,因为需要在系统中配置http/https代理. Ubuntu代理配置 配置方式非常简单,在~/.bashrc文件中增加: echo "exp ...

  7. zookeeper分布式锁的问题

    分布式锁的流程: 在zookeeper指定节点(locks)下创建临时顺序节点node_n 获取locks下所有子节点children 对子节点按节点自增序号从小到大排序 判断本节点是不是第一个子节点 ...

  8. HDU 4348 To the moon (主席树区间更新)

    题意:首先给你n个数,开始时间为0,最后按照操作输出 给你四种操作: 1. C l r d :  在(l,r)区间都加上d,时间加一2. Q l r :  询问现在(l,r)的区间和3. H l r ...

  9. Delphi_检查exe文件是否是"随机基址"

    ZC: cnpack 还是蛮好用的 1.代码: procedure TForm1.btnRandomizedBaseAddressClick(Sender: TObject); var pDosHdr ...

  10. js适配器模式

    适配器模式,将一个类的接口转换成客户希望的另外一个接口.适配器模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作. 系统的数据和行为都正确,但接口不符时,我们应该考虑用适配器,目的是使控制范 ...