本文由 飞羽流星(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的更多相关文章

  1. think php 上下架修改+jq静态批量删除+ajax删除+全选

    视图代码: <!doctype html> <html lang="en"> <head> <meta charset="UTF ...

  2. WPF DataGrid 控件的运用

    WPF DataGrid 控件的运用 运行环境:Window7 64bit,.NetFramework4.61,C# 6.0: 编者:乌龙哈里 2017-02-23 参考: King Cobra 博客 ...

  3. WPF DataGrid DataGridTemplateColumn 控制模板中控件

    <DataGrid Name="DG">                <DataGrid.Columns>                    < ...

  4. WPF: 实现带全选复选框的列表控件

    本文将说明如何创建一个带全选复选框的列表控件.其效果如下图:     这个控件是由一个复选框(CheckBox)与一个 ListView 组合而成.它的操作逻辑: 当选中“全选”时,列表中所有的项目都 ...

  5. Easyui datagrid加载数据时默认全选的问题

    问题描述: 最近使用 Easyui datagrid 展示数据,之前一直使用很正常,今天出现了一个怪异问题 加载数据后,只要点击选中列 ck 的任意行或多行,再刷新时整个datagrid的所有数据都 ...

  6. datagrid 绑定选中数据,列头全选

    成品图: xaml代码 <Grid> <DataGrid x:Name="datagrid" Height="Auto" Width=&quo ...

  7. WPF实现带全选复选框的列表控件

    本文将说明如何创建一个带全选复选框的列表控件.其效果如下图: 这个控件是由一个复选框(CheckBox)与一个 ListView 组合而成.它的操作逻辑: 当选中“全选”时,列表中所有的项目都会被选中 ...

  8. WPF DataGrid某列使用多绑定后该列排序失效,列上加入 SortMemberPath 设置即可.

    WPF DataGrid某列使用多绑定后该列排序失效 2011-07-14 10:59hdongq | 浏览 1031 次  悬赏:20 在wpf的datagrid中某一列使用了多绑定,但是该列排序失 ...

  9. WPF DataGrid自定义样式

    微软的WPF DataGrid中有很多的属性和样式,你可以调整,以寻找合适的(如果你是一名设计师).下面,找到我的小抄造型的网格.它不是100%全面,但它可以让你走得很远,有一些非常有用的技巧和陷阱. ...

  10. “WPF老矣,尚能饭否”—且说说WPF今生未来(上):担心

    近日微软公布了最新的WPF路线图,一片热议:对于老牌控件提供商葡萄城来说,这是WPF系列控件一个重要的机遇,因此,Spread Studio for WPF产品做了一次重要更新,并随着Spread S ...

随机推荐

  1. 关于package-lock.json

    前言 上篇文章我们了解了package.json,一般与它同时出现的还有一个package-lock.json,这两者又有什么关系呢?下面一起来了解吧. 介绍 package-lock.json 它会 ...

  2. [apue] 进程环境那些事儿

    main 函数与进程终止 众所周知,main 函数为 unix like 系统上可执行文件的"入口",然而这个入口并不是指链接器设置的程序起始地址,后者通常是一个启动例程,它从内核 ...

  3. Git命令详细使用指南

    Git命令详细使用指南 Git是一种广泛使用的版本控制系统,它可以帮助开发人员跟踪变更.协作项目和有效管理代码仓库.无论你是初学者还是有经验的用户,理解各种Git命令对于高效的代码管理至关重要. 安装 ...

  4. 《Python魔法大冒险》006 变量的迷雾

    小鱼和魔法师走了很久,终于来到了一个神秘的森林前.这片森林与众不同,它被一层厚厚的迷雾所包围,仿佛隐藏着无尽的秘密. 小鱼好奇地看着这片森林:"这是什么地方?" 魔法师:这是魔法森 ...

  5. 《流畅的Python》 读书笔记 230926

    写在最前面的话 缘由 关于Python的资料市面上非常多,好的其实并不太多. 个人认为,基础的,下面的都还算可以 B站小甲鱼 黑马的视频 刘江的博客 廖雪峰的Python课程 进阶的更少,<流畅 ...

  6. SpringBoot进阶教程(七十七)WebSocket

    WebSocket是一种在单个TCP连接上进行全双工通信的协议.WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据.在WebSocket API中,浏览器和 ...

  7. ⭐volatile⭐ 用volatile关键字则会从内存中直接读取变量的值

  8. 若依(ruoyi)开源系统保姆级实践-完成第一个页面

    一.案例描述 若依官网文档地址:http://doc.ruoyi.vip/ruoyi/document/hjbs.html 本教程主要内容,自定义数据库表,使用若依开源系统生成代码并配置权限. 若依环 ...

  9. EXCEL表格,当字段值超出单元格的区域时,如何不显示??

    问题阐述:当导出Excel表格的数据中的某一列字段的值超过单元格可以展示的范围,并且在Excel表格中展示为如下: 最终结果展示如下: 解决过程: 1.选中执行的单元格 2.右键选中"设置单 ...

  10. JDK21的虚拟线程是什么?和平台线程什么关系?

    虚拟线程(Virtual Thread)是 JDK 而不是 OS 实现的轻量级线程(Lightweight Process,LWP),由 JVM 调度.许多虚拟线程共享同一个操作系统线程,虚拟线程的数 ...