如何使用数据绑定基于属性值设置DataGrid的行背景 [英] How to set DataGrid's row Background, based on a property value using data bindings

查看:71
本文介绍了如何使用数据绑定基于属性值设置DataGrid的行背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的XAML代码中,我想基于某一特定行中对象的值设置每行的背景颜色。我有一个 z ObservableCollection ,每个 z 具有名为 State 的属性。我从 DataGrid 开始就是这样的:

In my XAML code, I want to set the Background color of each row, based on a value of the object in one specific row. I have an ObservableCollection of z, and each of the z has a property called State. I started out with something like this in my DataGrid:

<DataGrid.RowStyle>
    <Style TargetType="DataGridRow">
        <Setter Property="Background" 
                Value="{Binding z.StateId, Converter={StaticResource StateIdToColorConverter}}"/>
     </Style>
</DataGrid.RowStyle>

这是错误的方法,因为x不是我的ViewModel类的属性。

This is a wrong approach because x is not a property in my ViewModel class.

在我的ViewModel类中,我有一个 ObservableCollection< z> ,它是 ItemsSource DataGrid SelectedItem 类型的 z

In my ViewModel class I have an ObservableCollection<z> which is the ItemsSource of this DataGrid, and a SelectedItem of type z.

我可以将颜色绑定到 SelectedItem ,但这只会更改其中的一行 DataGrid

I could bind the color to SelectedItem, but this will only change one row in the DataGrid.

如何基于一个属性更改此行的背景颜色?

How can I, based on one property change this rows backgroundcolor?

推荐答案

使用 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>

这篇关于如何使用数据绑定基于属性值设置DataGrid的行背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆