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

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

问题描述

在我的 XAML 代码中,我想根据特定行中对象的值设置每一行的 Background 颜色.我有一个 zObservableCollection,每个 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,它是这个 DataGridItemsSource 和一个 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天全站免登陆