如何在 MVVM 轻型应用程序中对 DataGrid 行进行颜色编码

本文关键字:DataGrid 颜色 编码 MVVM 轻型 应用程序 | 更新日期: 2023-09-27 18:35:37

我正在将DataGrid绑定到模型,并希望根据数据更改行的颜色。 例如,如果模型属性错误为 true。 这是我目前拥有的:

<Grid Name="MyGrid">
    <DataGrid ItemsSource="{Binding Path=MyData}">
        <DataGrid.RowStyle>
            <Style TargetType="DataGridRow">                    
                <Style.Triggers>
                    <Trigger Property="{Binding Path=Error}" Value="true">
                        <Setter Property="Background" Value="Red"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </DataGrid.RowStyle>
        <DataGrid.Columns>
            <DataGridTextColumn Header="Field1" Binding="{Binding Field1}"/>
            <DataGridTextColumn Header="Field2" Binding="{Binding Field2}"/>
            <DataGridTextColumn Header="Field3" Binding="{Binding Field3}"/>
            <DataGridTextColumn Header="Field4" Binding="{Binding Field4}"/>
        </DataGrid.Columns>
    </DataGrid>

这种方法给了我编译时错误:

A 'Binding' cannot be set on the 'Property' property of type 'Trigger'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.

如何在 MVVM 轻型应用程序中对 DataGrid 行进行颜色编码

您可以使用 RowStyleSelector 来实现:

public class MyStyleSelector : StyleSelector
{
    public Style RegularStyle { get; set; }
    public Style ErrorStyle { get; set; }
    public override Style SelectStyle(object item, System.Windows.DependencyObject container)
    {
        var model = item as YourModel;
        // Avoid possible NullReferenceException
        if (model is null) return RegularStyle;
        // Here you determine which style to use based on the property in your model
        if (model.Error)
        {
            return ErrorStyle;
        }
        return RegularStyle;
    }
}

然后将其创建为 xaml 中的资源并定义样式

        <local:MyStyleSelector x:Key="rowStyleSelector">
            <local:MyStyleSelector.RegularStyle>
                <Style TargetType="DataGridRow">
                     <Setter Property="Background" Value="White"/>
                </Style>
            </local:MyStyleSelector.RegularStyle>
            <local:MyStyleSelector.ErrorStyle>
                <Style TargetType="DataGridRow">
                    <Setter Property="Background" Value="Red"/>
                </Style>
            </local:MyStyleSelector.ErrorStyle>
        </local:MyStyleSelector>

并在网格中使用它:

<DataGrid ItemsSource="{Binding SomeCollection}" RowStyleSelector="{StaticResource rowStyleSelector}">

希望这有帮助