上篇文章講述了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)原創,歡迎分享轉載,但禁止以原創二次發佈>>