WPF实现DataGrid行选中时可编辑单元格自动切换编辑模式的异常处理
问题核心
当前样式在单元格触发IsSelected=True时,无条件将单元格IsEditing设为True,缺少对绑定源属性可写权限的校验:
- 当单元格绑定的属性为只读时,
DataGrid会在编辑状态初始化时,尝试对只读源执行TwoWay回写操作,直接抛出System.InvalidOperationException: 'A TwoWay or OneWayToSource binding cannot work on the read-only property...' - 预期的交互效果(选中行时区分可编辑/不可编辑单元格的视觉反馈)本身是合理的,只需在多触发器逻辑中新增“绑定属性可写”的判断条件,即可实现无异常的交互。
实现方案
1. 新增绑定可写性校验的附加属性
编写WPF附加属性,在单元格加载时自动解析绑定路径、反射获取目标属性的可写状态,把结果存到单元格的附加属性上供触发器判断:
using System.Reflection; using System.Windows; using System.Windows.Controls; public static class DataGridCellHelper { /// <summary> /// 附加属性:标记当前单元格绑定的源属性是否具备可写权限 /// </summary> public static readonly DependencyProperty IsBoundPropertyWritableProperty = DependencyProperty.RegisterAttached( "IsBoundPropertyWritable", typeof(bool), typeof(DataGridCellHelper), new PropertyMetadata(defaultValue: false)); public static bool GetIsBoundPropertyWritable(DependencyObject obj) => (bool)obj.GetValue(IsBoundPropertyWritableProperty); public static void SetIsBoundPropertyWritable(DependencyObject obj, bool value) => obj.SetValue(IsBoundPropertyWritableProperty, value); /// <summary> /// 单元格加载时触发,自动校验绑定可写性 /// </summary> public static void OnDataGridCellLoaded(object sender, RoutedEventArgs e) { if (sender is not DataGridCell cell) return; // 仅对绑定列做可写性校验 if (cell.Column is not DataGridBoundColumn boundColumn) { SetIsBoundPropertyWritable(cell, false); return; } var bindingPath = boundColumn.Binding?.Path?.Path; if (string.IsNullOrWhiteSpace(bindingPath) || cell.DataContext == null) { SetIsBoundPropertyWritable(cell, false); return; } // 支持多级嵌套绑定路径校验(如 Order.Customer.Name) var propertyChain = bindingPath.Split('.'); var currentType = cell.DataContext.GetType(); PropertyInfo? targetProp = null; foreach (var propName in propertyChain) { targetProp = currentType.GetProperty( name: propName, bindingAttr: BindingFlags.Public | BindingFlags.Instance); if (targetProp == null) break; currentType = targetProp.PropertyType; } // 仅当属性存在且具备公开set访问器时,标记为可写 var isWritable = targetProp is { CanWrite: true }; SetIsBoundPropertyWritable(cell, isWritable); } }
2. 调整原有单元格样式
在多触发器逻辑中新增可写性判断条件,替换原先无条件设置IsEditing的逻辑,同时为两类单元格设置区分性视觉样式:
<!-- 引入附加属性所在的命名空间 --> xmlns:local="clr-namespace:你的项目命名空间" <Style TargetType="{x:Type DataGridCell}"> <!-- 绑定单元格Loaded事件,触发自动可写性校验 --> <EventSetter Event="Loaded" Handler="DataGridCellHelper.OnDataGridCellLoaded"/> <Style.Triggers> <!-- 可编辑单元格选中时的触发逻辑 --> <MultiTrigger> <MultiTrigger.Conditions> <Condition Property="IsSelected" Value="True"/> <Condition Property="local:DataGridCellHelper.IsBoundPropertyWritable" Value="True"/> </MultiTrigger.Conditions> <Setter Property="IsEditing" Value="True"/> <!-- 可编辑单元格选中的高亮提示 --> <Setter Property="Background" Value="#E3F2FD"/> </MultiTrigger> <!-- 不可编辑单元格选中时的触发逻辑(不进入编辑状态) --> <MultiTrigger> <MultiTrigger.Conditions> <Condition Property="IsSelected" Value="True"/> <Condition Property="local:DataGridCellHelper.IsBoundPropertyWritable" Value="False"/> </MultiTrigger.Conditions> <!-- 不可编辑单元格选中的低饱和提示 --> <Setter Property="Background" Value="#F5F5F5"/> </MultiTrigger> </Style.Triggers> </Style>
落地注意点
- 上述逻辑支持多层嵌套绑定的可写性校验,不会因为属性路径复杂出现判断遗漏
- 自定义模板列、操作按钮列这类非
DataGridBoundColumn的列类型,会默认被标记为不可写,从根源上避免无绑定单元格触发编辑状态异常 - 可写性判断仅校验源属性本身的公开set访问器,不会被值转换器、验证规则等附加绑定逻辑干扰判断
内容的提问来源于stack exchange,提问作者Ville
相关产品推荐
相关产品推荐

