在我的 XAML 代码中,我想设置 Background
每行的颜色,基于特定行中对象的值。我有一个ObservableCollection
的z
,以及 z
中的每一个有一个名为 State
的属性。我从我的 DataGrid
中开始使用类似的东西:
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="Background"
Value="{Binding z.StateId, Converter={StaticResource StateIdToColorConverter}}"/>
</Style>
</DataGrid.RowStyle>
这是一种错误的方法,因为 x 不是我的 ViewModel 类中的属性。
在我的 ViewModel 类中,我有一个 ObservableCollection<z>
这是 ItemsSource
这个DataGrid
,以及 SelectedItem
类型 z
.
我可以将颜色绑定(bind)到 SelectedItem
,但这只会更改 DataGrid
中的一行.
如何根据一个属性更改此行的背景颜色?
最佳答案
使用DataTrigger
:
<DataGrid ItemsSource="{Binding YourItemsSource}">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Binding="{Binding State}" Value="State1">
<Setter Property="Background" Value="Red"></Setter>
</DataTrigger>
<DataTrigger Binding="{Binding State}" Value="State2">
<Setter Property="Background" Value="Green"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
</DataGrid>
关于wpf - 如何使用数据绑定(bind)根据属性值设置 DataGrid 的行背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18053281/