项目中用到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"/>
- DataTable添加checkbox实现表格数据全选,单选(点选)
Datatables是一款jquery表格插件.它是一个高度灵活的工具,可以将任何HTML表格添加高级的交互功能. 分页,即时搜索和排序 几乎支持任何数据源:DOM, javascript, Ajax ...
- WPF 中获取DataGrid 模板列中控件的对像
WPF 中获取DataGrid 模板列中控件的对像 #region 当前选定行的TextBox获得焦点 /// <summary> /// 当前选定行的TextBox获得焦点 /// &l ...
- wpf中的datagrid绑定操作按钮是否显示或者隐藏
如图,需要在wpf中的datagrid的操作那列有个确认按钮,然后在某些条件下确认按钮可见,某些情况下不可见的,放在mvc里直接在cshtml页面中if..else就行了. 但是在wpf里不行..网上 ...
- DEV控件中GridView中的复选框与CheckBox实现联动的全选功能
最初的界面图如图1-1(全选框ID: cb_checkall DEV控件名称:gcCon ): 要实现的功能如下图(1-2 1-3 1-4)及代码所示: 图1-2 图1-3 图1-4 O(∩_∩ ...
- Android开发CheckBox控件,全选,反选,取消全选
在Android开发中我们经常会使用CheckBox控件,那么怎么实现CheckBox控件的全选,反选呢 首先布局我们的界面: <?xml version="1.0" enc ...
- WPF中嵌入Office编辑器(支持Word、Excel、PPT、Visio等)
现在有一个项目,需要使用wpf做一个简单的客户端,用来生成word.excel.ppt.visio等文档,这就需要能够在wpf中嵌入office的编辑器,并对office文档进行编辑. 在网上搜索了一 ...
- Winform开发 如何为dataGridView 添加CheckBox列,并获取选中行
//添加CheckBox列 DataGridViewCheckBoxColumn columncb = new DataGridViewCheckBoxColumn(); columncb.Heade ...
- CheckBox获取一组及全选
获取一组CheckBox: jQuery: $(function () { $("input[name=names]").click(function () { //获得所有的na ...
- checkbox实现单选,全选,反选,取消选
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools=&q ...
随机推荐
- Qt5.3.0的安装与测试
Qt5.3.0的安装与测试(交叉编译,用于arm,支持tslib触摸屏) 本次移植可以使用触摸屏. 首先下载源码包: http://download.qt.io/official_releases/q ...
- 如何单用户模式破解root密码&救援模式破解root密码
学了几天Linux,终于到了装逼时刻,看看如何破译别人的root密码,哈哈哈哈..... 单用户模式破解root密码 重置Centos 7 Root密码的方式 step1 - 在启动grub菜单,选择 ...
- Docker容器技术-基础与架构
一.什么是容器 容器是对应用程序及其依赖关系的封装. 1.容器的优点 容器与主机的操作系统共享资源,提高了效率,性能损耗低 容器具有可移植性 容器是轻量的,可同时运行数十个容器,模拟分布式系统 不必花 ...
- HAproxy 配置参数详解
HAproxy 配置参数详解 /etc/haproxy/haproxy.cfg # 配置文件 ----------------------------------------------------- ...
- DOCKER 简单操作
docker ps -a 列出所有镜像 docker start docder_name dcoker start docker_id 运行某个镜像 docker restart docker_nam ...
- 汇编笔记 RET
assume cs:code,ss:stack stack segment db dup() stack ends code segment mov ax,4c00h int 21h start: m ...
- Linux嵌入式 -- 内核 - 进程控制 和 调度
1. 进程四要素 1. 有一段程序供其执行.这段程序不一定是某个进程所专有,可以与其他进程共用. 2. 有进程专用的内核空间堆栈. 3. 在内核中有一个task_struct数据结构,即通常所说的&q ...
- Codeforces Round #374 (Div. 2) D. Maxim and Array 线段树+贪心
D. Maxim and Array time limit per test 2 seconds memory limit per test 256 megabytes input standard ...
- Django---model基础(单表)
ORM 一.映射关系: 表名<--------------->类名 字段<-------------->属性 表记录& ...
- jq中同个页面点击事件和回车事件
button元素,绑定一系列事件的时候,点击-回车-回车,会出现错误. 解决办法,就是把button变成a 详情是,一个页面中有点击按钮,按钮点击之后,出现弹框1,点击弹框1的确定,出现弹框2,点击弹 ...