.net - 将行颜色绑定(bind)到 MVVM 中的属性(取决于行中的数据)

标签 .net wpf silverlight mvvm datagrid

我有一个 datagrid谁的itemsSource绑定(bind)到 Customer 的集合我的 ViewModel 中的对象.

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

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

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

谢谢!

最佳答案

我会尝试使用 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>

关于.net - 将行颜色绑定(bind)到 MVVM 中的属性(取决于行中的数据),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14735744/

相关文章:

c# - 如何注释 C# 函数以表明参数返回时不为 null

c# - T4 引擎无法识别当前项目 namespace

c# - WPF 拼写检查终结器 - 安全句柄已关闭

c# - 如何获得定号之间的字符串中间部分?

.net - OleDbConnection、Excel 和连接池的问题

c# - 为什么 WPF 中没有点击事件?

c# - 从按钮打开窗口而不创建新的 windowFoo 实例

c# - 如何为 Silverlight 和 .NET 生成 WCF .cs 文件?

silverlight - 在没有服务架构的情况下使用Silverlight

c# - 在 Silverlight 中的运行时创建一个 ControlTemplate