wpf - 如何使用数据绑定(bind)根据属性值设置 DataGrid 的行背景

标签 wpf xaml wpfdatagrid

在我的 XAML 代码中,我想设置 Background每行的颜色,基于特定行中对象的值。我有一个ObservableCollectionz ,以及 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/

相关文章:

WPF:有没有办法只使用 PrintDialog 来选择目标打印机而不必提供 DocumentPaginator 类?

带有 ItemsSource 的 WPF ContextMenu - 如何在每个项目中绑定(bind)到 Command?

c# - 在 DataTemplate 内的 ListView 上添加 EventTrigger 导致 XamlParseException

唯一字段的 Wpf 数据网格验证规则

wpf - 放置在 DataGrid.DataGridTemplateColumn 中的 UserControl 中 PopupMenu 内的文本框永远不会获得 KeboardFocus?

c# - WPF - 在 Extended WPF Toolkit 中自定义 MessageBox 的样式

c# - 如何使用Prism的viewlocator将多个ViewModel连接到单个View?

c# - PresentationFramework.dll 中出现类型为 'System.Windows.Markup.XamlParseException' 的未处理异常

wpf - 使用 DataTrigger 设置 ScaleTransform 的属性

c# - 用户完成行编辑后如何获取DataGrid行数据?