WPF DataGrid開箱即用支持全部勾選的DataGridCheckBoxColumn

来源:https://www.cnblogs.com/Flithor/archive/2023/12/05/17877473.html
-Advertisement-
Play Games

上篇文章講述了C#多線程知識點,本文將介紹C#處理文件的知識點。在.NET開發領域,文件系統I/O是一個至關重要的主題,尤其是在處理文件、目錄和數據存儲方面。C#作為.NET平臺的主要編程語言,提供了豐富而強大的文件系統I/O功能,為開發人員提供了靈活的工具,使其能夠高效地處理文件操作。本文將介紹C ...


本文由 飛羽流星(Flithor/毛茸茸松鼠先生/Mr.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>
註意!
如果你在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)原創,歡迎分享轉載,但禁止以原創二次發佈>>


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 原文: https://openaigptguide.com/chatgpt-similar%20software/ ChatGPT是一款由美國OpenAI公司開發的人工智慧語言模型,類似的軟體有: 火山寫作(Volcano Writing):它是一款用戶友好的寫作軟體,可以自動生成具有創造性和連貫 ...
  • 前言 我python開發的GUI界面(圖形用戶界面)一直是tkinter,打包exe一直是Pyinstaller。但是打包出來的exe圖標、狀態欄圖標、窗體左上角圖標一直是預設的羽毛,我想自定義。 效果 最後使用base64創建臨時ico解決了該問題 步驟 創建icoToBase64.py,內容如下 ...
  • 在Java 21中,除了推出很多新特性之外,一些Bug修複,也需要註意一下。因為這些改變可能在升級的時候,造成影響。 Double.toString()和Float.toString()的精度問題修複 比如:對於Double.String(1e23): 在Java 19後,輸出內容為:1.0E23 ...
  • webjars類型的前端jar包 我們可以將公用的js,css,html,vue,shtml打包成一個jar,然後在其他項目中引用,這樣就不用每個項目都去引用一遍了,這樣就可以實現前端的公用了。 1.創建一個maven項目,添加依賴和插件 <dependencies> <!-- 依賴webjars- ...
  • pdf轉docx文檔是一個非常實用的功能,我只是簡單地實現了一個可視化界面供用戶操作。我這麼做的目的之一是想更多地掌握gradio的使用方法,同時也加強對Python流行第三方包的熟悉程度,因為這些第三方包是快速開發的關鍵。我也希望你能從中有所收穫,我已經公佈了本期的源碼地址,如果你覺得還不錯,或者... ...
  • 1. 什麼是Mvc 模型-視圖-控制器 (MVC) 體繫結構模式將應用程式分成 3 個主要組件組:視圖模型、視圖和控制器。 此模式有助於實現關註點分離。 使用此模式,用戶請求被路由到控制器,後者負責使用模型來執行用戶操作和/或檢索查詢結果。 控制器選擇要顯示給用戶的視圖,併為其提供所需的任何模型數據 ...
  • Options是微軟提供的選項模塊,該模塊依賴於容器使用。除了微軟的IServiceCollection,當然也可以使用其它的依賴註入容器。本文演示如何在prism中使用Options。 創建應用項目 創建一個Avalonia應用(或其它類型應用),然後使用NuGet包管理器添加Prism.DryI ...
  • 在.NET中,Microsoft.Extensions.Logging是一個廣泛使用的日誌庫,用於記錄應用程式的日誌信息。它提供了豐富的功能和靈活性,使開發人員能夠輕鬆地記錄各種類型的日誌,並將其輸出到不同的目標,包括日誌文件。本文將詳細介紹Microsoft.Extensions.Logging的 ...
一周排行
    -Advertisement-
    Play Games
  • 1、預覽地址:http://139.155.137.144:9012 2、qq群:801913255 一、前言 隨著網路的發展,企業對於信息系統數據的保密工作愈發重視,不同身份、角色對於數據的訪問許可權都應該大相徑庭。 列如 1、不同登錄人員對一個數據列表的可見度是不一樣的,如數據列、數據行、數據按鈕 ...
  • 前言 上一篇文章寫瞭如何使用RabbitMQ做個簡單的發送郵件項目,然後評論也是比較多,也是準備去學習一下如何確保RabbitMQ的消息可靠性,但是由於時間原因,先來說說設計模式中的簡單工廠模式吧! 在瞭解簡單工廠模式之前,我們要知道C#是一款面向對象的高級程式語言。它有3大特性,封裝、繼承、多態。 ...
  • Nodify學習 一:介紹與使用 - 可樂_加冰 - 博客園 (cnblogs.com) Nodify學習 二:添加節點 - 可樂_加冰 - 博客園 (cnblogs.com) 介紹 Nodify是一個WPF基於節點的編輯器控制項,其中包含一系列節點、連接和連接器組件,旨在簡化構建基於節點的工具的過程 ...
  • 創建一個webapi項目做測試使用。 創建新控制器,搭建一個基礎框架,包括獲取當天日期、wiki的請求地址等 創建一個Http請求幫助類以及方法,用於獲取指定URL的信息 使用http請求訪問指定url,先運行一下,看看返回的內容。內容如圖右邊所示,實際上是一個Json數據。我們主要解析 大事記 部 ...
  • 最近在不少自媒體上看到有關.NET與C#的資訊與評價,感覺大家對.NET與C#還是不太瞭解,尤其是對2016年6月發佈的跨平臺.NET Core 1.0,更是知之甚少。在考慮一番之後,還是決定寫點東西總結一下,也回顧一下.NET的發展歷史。 首先,你沒看錯,.NET是跨平臺的,可以在Windows、 ...
  • Nodify學習 一:介紹與使用 - 可樂_加冰 - 博客園 (cnblogs.com) Nodify學習 二:添加節點 - 可樂_加冰 - 博客園 (cnblogs.com) 添加節點(nodes) 通過上一篇我們已經創建好了編輯器實例現在我們為編輯器添加一個節點 添加model和viewmode ...
  • 前言 資料庫併發,數據審計和軟刪除一直是數據持久化方面的經典問題。早些時候,這些工作需要手寫複雜的SQL或者通過存儲過程和觸發器實現。手寫複雜SQL對軟體可維護性構成了相當大的挑戰,隨著SQL字數的變多,用到的嵌套和複雜語法增加,可讀性和可維護性的難度是幾何級暴漲。因此如何在實現功能的同時控制這些S ...
  • 類型檢查和轉換:當你需要檢查對象是否為特定類型,並且希望在同一時間內將其轉換為那個類型時,模式匹配提供了一種更簡潔的方式來完成這一任務,避免了使用傳統的as和is操作符後還需要進行額外的null檢查。 複雜條件邏輯:在處理複雜的條件邏輯時,特別是涉及到多個條件和類型的情況下,使用模式匹配可以使代碼更 ...
  • 在日常開發中,我們經常需要和文件打交道,特別是桌面開發,有時候就會需要載入大批量的文件,而且可能還會存在部分文件缺失的情況,那麼如何才能快速的判斷文件是否存在呢?如果處理不當的,且文件數量比較多的時候,可能會造成卡頓等情況,進而影響程式的使用體驗。今天就以一個簡單的小例子,簡述兩種不同的判斷文件是否... ...
  • 前言 資料庫併發,數據審計和軟刪除一直是數據持久化方面的經典問題。早些時候,這些工作需要手寫複雜的SQL或者通過存儲過程和觸發器實現。手寫複雜SQL對軟體可維護性構成了相當大的挑戰,隨著SQL字數的變多,用到的嵌套和複雜語法增加,可讀性和可維護性的難度是幾何級暴漲。因此如何在實現功能的同時控制這些S ...