本文由 飛羽流星(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)原創,歡迎分享轉載,但禁止以原創二次釋出>>