1

我有一个who绑定到我datagrid的.itemsSourceCustomerViewModel

每个Customer对象都有一个布尔属性IsComplete(不是数据网格中的可见列)。IsComplete如果为假,如何将整行染成红色?

我是 MVVM 概念的新手,所以我仍然无法理解它。到目前为止,我看到的示例似乎并未根据单个属性的内容为整行着色。

如果需要的话,我愿意重构。

谢谢!

4

2 回答 2

2

我会尝试为此使用RowStyleSelector。它允许您定义不同的行样式,并根据该行中的数据每行选择一个。

本质上,您定义了一个继承StyleSelector并覆盖该SelectStyle方法的类。这就是您放置逻辑以根据行数据选择样式的地方 -item包含行数据:

public class MyStyleSelector : StyleSelector
{
    public override Style SelectStyle(object item, DependencyObject container)
    {
        if (item is Customer)
        {
            return ((Customer)item).IsComplete ? 
                App.Current.Resources["RedRowStyle"] :
                App.Current.Resources["NormalRowStyle"]
        }
        return base.SelectStyle(item, container);
    }
}

将资源添加到应用程序的资源字典中:

<Application.Resources>
    <Style TargetType="DataGridRow" x:Key="NormalRowStyle">
    </Style>
    <Style TargetType="DataGridRow" BasedOn="{StaticResource NormalRowStyle}" x:Key="RedRowStyle">
        <Setter Property="Background" Value="Red" />
    </Style>
</Application.Resources>

然后,您通过静态资源引用选择器,例如:

<Window>
    <Window.Resources>
        <local:MyStyleSelector x:Key="MyStyleSelector" />
    </Window.Resources>

    <DataGrid RowStyleSelector="{StaticResource MyStyleSelector}">
        <!-- ... -->
    </DataGrid>
</Window>
于 2013-02-06T18:03:14.953 回答
1

在 MVVM 样式中,创建一个 CustomerViewModel 并定义属性 CustomerColor(与 IsComplete 属性值相关)。

试试这个:

<DataGrid>
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="Background">
               <Setter.Value>
                   <SolidColorBrush Color="{Binding CustomerColor}"/>
              </Setter.Value>
            </Setter>
        </Style>
    </DataGrid.RowStyle>
</DataGrid>
于 2013-02-06T18:09:25.907 回答