WPF DataGrid真正意义上开箱即用的原生可动态更新全选状态的DataGridCheckBox
本文由 飞羽流星(Flithor/毛茸茸松鼠先生/Squirrel.Downy)原创,欢迎分享转载,但禁止以原创二次发布
原位地址:https://www.cnblogs.com/Flithor/p/17877473.html
以往在WPF的DataGrid上实现实时勾选交互非常麻烦,要用DataGridTemplateColumn写样式还要写一些后端代码,还有绑定和转换器,或者处理事件。
但是现在都不需要了,使用开箱即用的DataGridCheckAllColumn,简化你的勾选代码实现!
它支持列表筛选反馈,支持虚拟化,支持单向勾选变化的反向通知。
而且非常简单好用:
<DataGrid.Columns>
<!-- 像使用DataGridCheckBoxColumn那样使用和绑定就行 -->
<fc:DataGridCheckAllColumn Binding="{Binding IsChecked}" />
<!-- 其它列 -->
<DataGridTextColumn Binding="{Binding EntityName}" />
</DataGrid.Columns>
DataGridCheckAllColumn类的实现:
// 代码作者: 飞羽流星(Flithor/Mr. Squirrel.Downy/毛茸茸松鼠先生)
// 开源许可: MIT
// =======警告=======
// 使用开源代码的风险自负 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Media; using Expression = System.Linq.Expressions.Expression; namespace Flithor_Codes
{
/// <summary>
/// 一个支持勾选所有的DataGrid列
/// </summary>
public class DataGridCheckAllColumn : DataGridBoundColumn
{
#region 私有字段
//列头中的CheckBox
private readonly CheckBox checkAllCheckBox;
//所属DataGrid控件
private DataGrid? ownerDatagrid;//所属DataGrid控件的列表版本,如果版本号改变则说明列表改变
private Func<int>? getInnerEnumeratorVersion;
//缓存的列表版本号
private int cachedInnerVersion;
//CheckBox的默认样式
private static Style _defaultElementStyle;
#endregion #region 初始化控件
public static Style DefaultElementStyle
{
get
{
if (_defaultElementStyle == null)
{
var style = new Style(typeof(CheckBox))
{
Setters =
{
new Setter(UIElement.FocusableProperty, false),
new Setter(CheckBox.HorizontalAlignmentProperty, HorizontalAlignment.Center),
new Setter(CheckBox.VerticalAlignmentProperty, VerticalAlignment.Center)
}
}; style.Seal();
_defaultElementStyle = style;
} return _defaultElementStyle;
}
} static DataGridCheckAllColumn()
{
//重写单元格元素默认样式
ElementStyleProperty.OverrideMetadata(typeof(DataGridCheckBoxColumn), new FrameworkPropertyMetadata(DefaultElementStyle));
//使列默认只读
IsReadOnlyProperty.OverrideMetadata(typeof(DataGridCheckAllColumn), new FrameworkPropertyMetadata(true));
//不允许重排此列
CanUserReorderProperty.OverrideMetadata(typeof(DataGridCheckAllColumn), new FrameworkPropertyMetadata(false));
//不允许修改此列宽度
CanUserResizeProperty.OverrideMetadata(typeof(DataGridCheckAllColumn), new FrameworkPropertyMetadata(false));
//不允许点击列头排序项目
CanUserSortProperty.OverrideMetadata(typeof(DataGridCheckAllColumn), new FrameworkPropertyMetadata(false));
} public DataGridCheckAllColumn()
{
//设置列头
Header = checkAllCheckBox = new CheckBox();
} protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
{
if (ownerDatagrid != null) return; ownerDatagrid = GetParentDataGrid();
if (ownerDatagrid == null) return; InitInnerVersionDetect(ownerDatagrid.Items); ((INotifyPropertyChanged)ownerDatagrid.Items).PropertyChanged += OnPropertyChanged; //如果DataGrid当前已有项目,则初始化绑定
checkAllCheckBox.IsEnabled = ownerDatagrid.Items.Count > 0;
if (checkAllCheckBox.IsEnabled)
ResetCheckCurrentAllBinding();
}
//寻找所属DataGrid控件(如果还没初始化完毕,可能返回空值)
private DataGrid GetParentDataGrid()
{
DependencyObject elment = checkAllCheckBox;
do
{
elment = VisualTreeHelper.GetParent(elment);
}
while (elment != null && !(elment is DataGrid));
return elment as DataGrid;
}
#endregion #region 构建单元格元素(方法的功能不言自明)
protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
{
return GenerateCheckBox(false, cell, dataItem);
} protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem)
{
return GenerateCheckBox(true, cell, dataItem);
} private CheckBox GenerateCheckBox(bool isEditing, DataGridCell cell, object dataItem)
{
var checkBox = new CheckBox();
ApplyStyle(isEditing, checkBox);
ApplyBinding(dataItem, checkBox);
return checkBox;
} private void ApplyBinding(object dataItem, CheckBox checkBox)
{
var binding = CloneBinding(Binding, dataItem);
if (binding is Binding newBinding)
{
newBinding.Mode = BindingMode.TwoWay;
newBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
}
BindingOperations.ClearBinding(checkBox, CheckBox.IsCheckedProperty);
checkBox.SetBinding(CheckBox.IsCheckedProperty, binding);
} internal void ApplyStyle(bool isEditing, FrameworkElement element)
{
Style style = PickStyle(isEditing);
if (style != null)
{
element.Style = style;
}
} private Style PickStyle(bool isEditing)
{
Style style = isEditing ? EditingElementStyle : ElementStyle;
if (isEditing && (style == null))
{
style = ElementStyle;
} return style;
}
#endregion #region 更新绑定
private void OnPropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (ownerDatagrid == null || e.PropertyName != nameof(ownerDatagrid.Items.Count))
return;
//如果项目数量发生改变意味着列表更新了
if (ownerDatagrid.Items.Count == 0)
{
//如果列表空了,那就移除绑定并禁用列头勾选控件
BindingOperations.ClearBinding(checkAllCheckBox, CheckBox.IsCheckedProperty);
checkAllCheckBox.IsEnabled = false;
}
else
{
//否则基于当前列表显示项更新绑定
ResetCheckCurrentAllBinding();
checkAllCheckBox.IsEnabled = true;
}
} private void ResetCheckCurrentAllBinding()
{
//如果列表版本号改变则更新,否则无需更新
if (ownerDatagrid == null || !InnerVersionChanged()) return; var checkAllBinding = new MultiBinding
{
Converter = AllBoolStatusConverter.Default,
Mode = BindingMode.TwoWay
};
//基于所有列表显示项创建绑定
var currentItems = ownerDatagrid.Items.OfType<object>().ToList();
foreach (var item in currentItems)
{
checkAllBinding.Bindings.Add(CloneBinding((Binding)Binding, item));
} //清除旧绑定
BindingOperations.ClearBinding(checkAllCheckBox, CheckBox.IsCheckedProperty); checkAllCheckBox.SetBinding(CheckBox.IsCheckedProperty, checkAllBinding);
} //创建获取内部列表版本号的委托
private void InitInnerVersionDetect(ItemCollection itemCollection)
{
//Timestamp属性是内部列表的版本号标识,用于表示列表变更的次数
var collectionTimestampProerty = itemCollection.GetType()
.GetProperty("Timestamp", BindingFlags.Instance | BindingFlags.NonPublic);
//使用Linq的Expression来构建访问Timestamp属性的委托方法
getInnerEnumeratorVersion = Expression.Lambda<Func<int>>(Expression.Property(
Expression.Constant(itemCollection),
collectionTimestampProerty)).Compile();
}
//检查内部列表是否发生了更新
private bool InnerVersionChanged()
{
var currentInnerVersion = getInnerEnumeratorVersion!.Invoke();
if (currentInnerVersion != cachedInnerVersion)
{
cachedInnerVersion = currentInnerVersion;
return true;
} return false;
}
//基于已有绑定对象创建一个副本,使用指定的数据源
private static BindingBase CloneBinding(BindingBase bindingBase, object source)
{
switch (bindingBase)
{
case Binding binding:
var resultBinding = new Binding
{
Source = source,
AsyncState = binding.AsyncState,
BindingGroupName = binding.BindingGroupName,
BindsDirectlyToSource = binding.BindsDirectlyToSource,
Converter = binding.Converter,
ConverterCulture = binding.ConverterCulture,
ConverterParameter = binding.ConverterParameter,
//ElementName = binding.ElementName,
FallbackValue = binding.FallbackValue,
IsAsync = binding.IsAsync,
Mode = binding.Mode,
NotifyOnSourceUpdated = binding.NotifyOnSourceUpdated,
NotifyOnTargetUpdated = binding.NotifyOnTargetUpdated,
NotifyOnValidationError = binding.NotifyOnValidationError,
Path = binding.Path,
//RelativeSource = binding.RelativeSource,
StringFormat = binding.StringFormat,
TargetNullValue = binding.TargetNullValue,
UpdateSourceExceptionFilter = binding.UpdateSourceExceptionFilter,
UpdateSourceTrigger = binding.UpdateSourceTrigger,
ValidatesOnDataErrors = binding.ValidatesOnDataErrors,
ValidatesOnExceptions = binding.ValidatesOnExceptions,
XPath = binding.XPath,
}; foreach (var validationRule in binding.ValidationRules)
{
resultBinding.ValidationRules.Add(validationRule);
} return resultBinding;
case MultiBinding multiBinding:
var resultMultiBinding = new MultiBinding
{
BindingGroupName = multiBinding.BindingGroupName,
Converter = multiBinding.Converter,
ConverterCulture = multiBinding.ConverterCulture,
ConverterParameter = multiBinding.ConverterParameter,
FallbackValue = multiBinding.FallbackValue,
Mode = multiBinding.Mode,
NotifyOnSourceUpdated = multiBinding.NotifyOnSourceUpdated,
NotifyOnTargetUpdated = multiBinding.NotifyOnTargetUpdated,
NotifyOnValidationError = multiBinding.NotifyOnValidationError,
StringFormat = multiBinding.StringFormat,
TargetNullValue = multiBinding.TargetNullValue,
UpdateSourceExceptionFilter = multiBinding.UpdateSourceExceptionFilter,
UpdateSourceTrigger = multiBinding.UpdateSourceTrigger,
ValidatesOnDataErrors = multiBinding.ValidatesOnDataErrors,
ValidatesOnExceptions = multiBinding.ValidatesOnDataErrors,
}; foreach (var validationRule in multiBinding.ValidationRules)
{
resultMultiBinding.ValidationRules.Add(validationRule);
} foreach (var childBinding in multiBinding.Bindings)
{
resultMultiBinding.Bindings.Add(CloneBinding(childBinding, source));
} return resultMultiBinding;
case PriorityBinding priorityBinding:
var resultPriorityBinding = new PriorityBinding
{
BindingGroupName = priorityBinding.BindingGroupName,
FallbackValue = priorityBinding.FallbackValue,
StringFormat = priorityBinding.StringFormat,
TargetNullValue = priorityBinding.TargetNullValue,
}; foreach (var childBinding in priorityBinding.Bindings)
{
resultPriorityBinding.Bindings.Add(CloneBinding(childBinding, source));
} return resultPriorityBinding;
default:
throw new NotSupportedException("Failed to clone binding");
}
}
/// <summary>
/// 用于合并所有bool值到一个值的多值转换器
/// </summary>
private class AllBoolStatusConverter : IMultiValueConverter
{
public static readonly AllBoolStatusConverter Default = new AllBoolStatusConverter(); public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values.Length == 0 || values.OfType<bool>().Count() != values.Length)
return false;
// 检查所有项是否和第一项相同
var firstStatus = values.First(); foreach (var value in values)
{
//如果有不同就返回null,表示第三态
if (!Equals(value, firstStatus))
return null;
} return firstStatus;
} public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
//如果汇总的值发生变化则更新所有项目
var res = new object[targetTypes.Length];
Array.Fill(res, Equals(value, true));
return res;
}
}
#endregion
}
}
<<这是一条标识脚本盗传狗的隐形水印>>
<<本文由 飞羽流星(Flithor/毛茸茸松鼠先生/Squirrel.Downy)原创,欢迎分享转载,但禁止以原创二次发布>>
WPF DataGrid真正意义上开箱即用的原生可动态更新全选状态的DataGridCheckBox的更多相关文章
- think php 上下架修改+jq静态批量删除+ajax删除+全选
视图代码: <!doctype html> <html lang="en"> <head> <meta charset="UTF ...
- WPF DataGrid 控件的运用
WPF DataGrid 控件的运用 运行环境:Window7 64bit,.NetFramework4.61,C# 6.0: 编者:乌龙哈里 2017-02-23 参考: King Cobra 博客 ...
- WPF DataGrid DataGridTemplateColumn 控制模板中控件
<DataGrid Name="DG"> <DataGrid.Columns> < ...
- WPF: 实现带全选复选框的列表控件
本文将说明如何创建一个带全选复选框的列表控件.其效果如下图: 这个控件是由一个复选框(CheckBox)与一个 ListView 组合而成.它的操作逻辑: 当选中“全选”时,列表中所有的项目都 ...
- Easyui datagrid加载数据时默认全选的问题
问题描述: 最近使用 Easyui datagrid 展示数据,之前一直使用很正常,今天出现了一个怪异问题 加载数据后,只要点击选中列 ck 的任意行或多行,再刷新时整个datagrid的所有数据都 ...
- datagrid 绑定选中数据,列头全选
成品图: xaml代码 <Grid> <DataGrid x:Name="datagrid" Height="Auto" Width=&quo ...
- WPF实现带全选复选框的列表控件
本文将说明如何创建一个带全选复选框的列表控件.其效果如下图: 这个控件是由一个复选框(CheckBox)与一个 ListView 组合而成.它的操作逻辑: 当选中“全选”时,列表中所有的项目都会被选中 ...
- WPF DataGrid某列使用多绑定后该列排序失效,列上加入 SortMemberPath 设置即可.
WPF DataGrid某列使用多绑定后该列排序失效 2011-07-14 10:59hdongq | 浏览 1031 次 悬赏:20 在wpf的datagrid中某一列使用了多绑定,但是该列排序失 ...
- WPF DataGrid自定义样式
微软的WPF DataGrid中有很多的属性和样式,你可以调整,以寻找合适的(如果你是一名设计师).下面,找到我的小抄造型的网格.它不是100%全面,但它可以让你走得很远,有一些非常有用的技巧和陷阱. ...
- “WPF老矣,尚能饭否”—且说说WPF今生未来(上):担心
近日微软公布了最新的WPF路线图,一片热议:对于老牌控件提供商葡萄城来说,这是WPF系列控件一个重要的机遇,因此,Spread Studio for WPF产品做了一次重要更新,并随着Spread S ...
随机推荐
- OpenLDAP服务器搭建
一.关闭防火墙和selinux [root@localhost ~]# systemctl stop firewalld.service [root@localhost ~]# systemctl d ...
- 命令行安装ipa包
我们可以通过ssh连接我们的iphone,来使用命令行安装ipa包 itunnel_mux.exe --lport 9993 --iport 22 itunnel_mux.exe --lport 99 ...
- MySQL允许远程登录的授权方法
泛授权方式 数据库本地直接登录上数据库: mysql -h localhost -u root 然后执行以下命令,授权完后直接就可以远程连接上.mysql>GRANT ALL PRIVILEGE ...
- tomcat配置域名绑定项目
有时候我们需要根据访问的不同域名,对应tomcat中不同的项目例如:一个网站同时做了两套,pc版和手机版.手机版对应的域名是m.we-going.com,就需要在tomcat配置文件中加入以下代码:& ...
- [错误] SQL logic error near "date": syntax error
问题的来源 今天把一个项目的数据库从MySQL改到Sqlite 调试时发生了这个错误. 百度又看不懂英文(很多是国外发的), 就折腾了一下 原因 C# Sqlite 不能使用参数前缀"?&q ...
- Windows 某些软件显示"口口"解决办法
和乱码不同,文字变成"口口",一般是语言环境出错了. 解决办法 开始->控制面板->区域 (时钟.语言和区域)->区域:更改设置->管理->非 Uni ...
- Python 潮流周刊#21:如何提升及测量 Python 代码的性能?
你好,我是猫哥.这里每周分享优质的 Python.AI 及通用技术内容,大部分为英文.标题取自其中三则分享,不代表全部内容都是该主题,特此声明. 本周刊由 Python猫 出品,精心筛选国内外的 25 ...
- Android下音视频对讲演示程序(声学回音消除、噪音抑制、语音活动检测、自动增益控制、自适应抖动缓冲)(2023年07月13日更新)
Android下音视频对讲演示程序 必读说明 简介 本软件根据<道德经>为核心思想而设计,实现了两个设备之间进行音视频对讲,一般可用于楼宇对讲.智能门铃对讲.企业员工对讲.智能对讲机. ...
- 轻松合并Excel工作表:Java批量操作优化技巧
摘要:本文由葡萄城技术团队于博客园原创并首发.转载请注明出处:葡萄城官网,葡萄城为开发者提供专业的开发工具.解决方案和服务,赋能开发者. 前言 在Excel中设计表单时,我们经常需要对收集的信息进行统 ...
- NFT(数字藏品)热度没了?这玩意是机会还是泡沫?
感谢你阅读本文! 大家好,今天分享一下NFT(数字藏品)这个领域,虽然今天的NFT已经没有之前那么火热,不过市场上依旧还是有很多平台存在,有人离开,也有人不断进来,所以很有必要再分析一番. 需要注意的 ...