根据数据表错误设置wpf Datagrid单元格背景

问题描述 投票:0回答:1
wpf datatable datagrid
1个回答
0
投票

您可以使用一个转换器来调用

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
更改为程序集和命名空间的名称。

© www.soinside.com 2019 - 2024. All rights reserved.