您可以使用一个转换器来调用
GetColumnError
的 DataRow
方法:
public class ErrorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
DataRow row = value as DataRow;
string columnName = parameter as string;
return row != null && !string.IsNullOrEmpty(columnName) && !string.IsNullOrEmpty(row.GetColumnError(columnName));
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
然后处理
AutoGeneratingColumn
为每列定义自定义 CellTemplate
:
myDataGrid.AutoGeneratingColumn += (s, e) =>
{
string CellStyle =
"<Style xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"" +
" xmlns:local=\"clr-namespace:WpfApp1;assembly=WpfApp1\" TargetType=\"DataGridCell\">" +
"<Style.Triggers>" +
"<DataTrigger Value=\"True\">" +
"<DataTrigger.Binding>" +
$"<Binding Path=\"Row\" ConverterParameter=\"{e.PropertyName}\">" +
"<Binding.Converter>" +
"<local:ErrorConverter />" +
"</Binding.Converter>" +
"</Binding>" +
"</DataTrigger.Binding>" +
"<Setter Property=\"Background\" Value=\"Yellow\"/>" +
"</DataTrigger>" +
"</Style.Triggers>" +
"</Style>";
e.Column.CellStyle = XamlReader.Parse(CellStyle) as Style;
};
记住将
WpfApp1
更改为程序集和命名空间的名称。