本文由 飞羽流星(Flithor/毛茸茸松鼠先生/Mr.Squirrel.Downy)原创,欢迎分享转载,但禁止以原创二次发布
原文地址:https://www.cnblogs.com/Flithor/p/17877473.html

以往在WPF的DataGrid上实现实时勾选交互非常麻烦,要用DataGridTemplateColumn写样式还要写一些后端代码,还有绑定和转换器,或者处理事件。

但是现在都不需要了,使用开箱即用的DataGridCheckAllColumn,简化你的勾选代码实现!

它支持列表筛选变化反馈,支持虚拟化,支持单项勾选变化的更新反馈。

效果预览:

WPF DataGrid开箱即用支持全部勾选的DataGridCheckBoxColumn-LMLPHP

而且非常简单好用

<DataGrid.Columns>
    <!-- 像使用DataGridCheckBoxColumn那样使用和绑定就行 -->
    <fc:DataGridCheckAllColumn Binding="{Binding IsChecked}" />
    <!-- 其它列 -->
    <DataGridTextColumn Binding="{Binding EntityName}" />
</DataGrid.Columns>
注意!
如果你在DataGrid上设置了VirtualizingPanel.IsVirtualizing="True"应用虚拟化
需要同时设置VirtualizingPanel.VirtualizationMode="Standard",避免出现绑定实例错误的Bug

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.Runtime.Remoting.Messaging;
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(DataGridCheckAllColumn), 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];
                for (int i = 0; i < res.Length; i++)
                    res[i] = value;
                return res;
            }
        }
        #endregion
    }
}

<<这是一条标识脚本盗传狗的隐形水印>>

<<本文由 飞羽流星(Flithor/毛茸茸松鼠先生/Mr.Squirrel.Downy)原创,欢迎分享转载,但禁止以原创二次发布>>

12-07 10:33