这就是我使用转换器解决它的方法。
拥有一个带有指定列的 DataGrid,每个列的定义如下:
<MyOwn:CustomDataGridColumn Header="Column1Header" Name="Column1" ElementStyle="{StaticResource ElementStyleWithMultiConverterAndTriggers}">
<MyOwn:CustomDataGridColumn.Binding>
<Binding Path="RowModel.ColumnName" ValidatesOnDataErrors="True" >
<Binding.ValidationRules>
<Validators:CustomCellDataInfoValidationRule />
</Binding.ValidationRules>
</Binding>
</MyOwn:CustomDataGridColumn.Binding>
</MyOwn:CustomDataGridColumn>
然后我附加了一个带有 DataTriggers 的样式,如下所示:
<Style TargetType="{x:Type TextBlock}" x:Key="ElementStyleWithMultiConverterAndTriggers">
<Style.Resources>
<Utils:ErrorTypeConverter x:Key="ErrorTypeConverter"/>
</Style.Resources>
<Setter Property="TextBlock.Padding" Value="2" />
<Setter Property="Validation.ErrorTemplate" Value="{x:Null}" />
<Style.Triggers>
<DataTrigger Value="Critical" >
<DataTrigger.Binding>
<MultiBinding Converter="{StaticResource ErrorTypeConverter}">
<Binding RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type DataGridCell}}" Path="Column.Name"/>
<Binding Path="RowModel" /> <!--Sending the whole row object as one of the parameters to the converter-->
</MultiBinding>
</DataTrigger.Binding>
<Setter Property="Background" Value="Red"/>
</DataTrigger>
<DataTrigger Value="Warning" >
<DataTrigger.Binding>
<MultiBinding Converter="{StaticResource ErrorTypeConverter}">
<Binding RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type DataGridCell}}" Path="Column.Name"/>
<Binding Path="RowModel" />
</MultiBinding>
</DataTrigger.Binding>
<Setter Property="Background" Value="Yellow"/>
</DataTrigger>
</Style.Triggers>
</Style>
MultiValueConverter 看起来像这样。
public class ErrorTypeConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
var rowObject = values[1] as RowModel;
var param = values[0].ToString();
if (rowObject == null) return "";
if (rowObject.ValidationClass.Any())
{
var validationErrors = rowObject.ValidationClass.FirstOrDefault(x => x.SourceColumn == param);
if (validationErrors != null )
return validationErrors.Tag; // Will return "Critical" or "Warning"
}
return "";
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
这个套件是我的需要,但在搜索结果中有 1000 多行的 DataGrid 上却很重。但总比没有好。欢迎任何改进。