项目中用到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 ...
随机推荐
- Linux的XServer
Moblin Core是在Gnome Mobile的平台上建立.我以前玩Linux,提交的都和图像没有关系,连Xwindows都不用启动,开机后直接进入文本命令行,所以这方面了解得很少,需要学习一下, ...
- C语言math.h库函数中atan与atan2的区别
源: C语言math.h库函数中atan与atan2的区别 C语言中的atan和atan2
- MongoDB 使用Limit和Skip完成分页 和游标(二)
//$slice操作符返回文档中指定数组的内部值 //查询出Jim书架中第2~4本书 db.persons.find({name:"jim"},{books:{"$sli ...
- 断点续传JAVA实现
支持H5 Video标签播放,迅雷下载 /** * 断点续传工具 * @author lxycx_xc * 时间:2017年11月30日 */ public class BreakpointResum ...
- 通过加载Xib文件来创建UITableViewCell造成复用数据混乱问题方案
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPa ...
- maven install 找不到自定义jar包
解决方案是在Prefernces-->Maven-->user Settings 里面点击Update settings 然后就好了.因为默认你配置settings.xml指向你的类库的时 ...
- spark HelloWorld程序(scala版)
使用本地模式,不需要安装spark,引入相关JAR包即可: <dependency> <groupId>org.apache.spark</groupId> < ...
- Codeforces Round #273 (Div. 2) A , B , C 水,数学,贪心
A. Initial Bet time limit per test 1 second memory limit per test 256 megabytes input standard input ...
- c++ Const关键字
转自:http://blog.csdn.net/Eric_Jo/article/details/4138548 C++中的const关键字的用法非常灵活,而使用const将大大改善程序的健壮性,本人根 ...
- jsp中的taglib
JSP中使用Taglib 标准的JSP标记可以调用JavaBeans组件或者执行客户的请求,这大大降低了JSP开发的复杂度和维护量.JSP技术也允许你自定义的taglib,其实换句话说,taglib可 ...