我有一个 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/