0

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

<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.
4

1 回答 1

3

您可以为此使用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}">

希望这可以帮助

于 2013-10-15T11:36:55.797 回答