基于DataGridCell值类型的WPF Trigger实现错误排查咨询
问题排查与修复方案
你代码的问题一共涉及两处核心错误,分别是绑定逻辑错误和转换逻辑适配问题:
1. DataTrigger绑定路径错误
你当前的Binding没有指定Path,指定RelativeSource={RelativeSource Self}时,会直接把DataGridCell实例传入转换器,而不是单元格承载的实际业务值,所以转换器返回的永远是typeof(DataGridCell),不可能匹配到DateTime类型。
如果只是快速验证效果,针对非模板列可以先修改绑定路径到单元格的Content属性:
<DataTrigger Binding="{Binding Path=Content, RelativeSource={RelativeSource Self}, Converter={StaticResource DataTypeConverter}}" Value="{x:Type sys:DateTime}">
2. 转换逻辑适配问题
如果你使用的是DataGridTextColumn这类默认自动生成列,WPF会自动把原始值格式化为字符串展示在单元格里,此时Content属性拿到的是字符串类型,还是无法匹配到DateTime类型。这种情况可以直接修改转换器,从DataGridCell对象中解析原始绑定值,不需要改XAML绑定:
public class class_converter_data_type : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is not DataGridCell cell) return Binding.DoNothing; // 获取列的绑定配置 if (cell.Column is DataGridBoundColumn boundColumn && boundColumn.Binding is Binding binding) { var rowData = cell.DataContext; if (rowData == null) return Binding.DoNothing; // 从行数据源中取原始属性值 var prop = rowData.GetType().GetProperty(binding.Path.Path); if (prop == null) return Binding.DoNothing; var propValue = prop.GetValue(rowData); return propValue?.GetType() ?? Binding.DoNothing; } return Binding.DoNothing; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } }
额外注意事项
请确保XAML头部已经引入System命名空间声明,否则{x:Type sys:DateTime}会报错:
xmlns:sys="clr-namespace:System;assembly=mscorlib"
内容的提问来源于stack exchange,提问作者Murulimadhav
相关产品推荐
相关产品推荐

