首页 > 解决方案 > WPF DataGrid 行的颜色多绑定(也)拥有 IsSelected 属性?

问题描述

我有一个 DataGrid,其中 ItemsSource 连接到 SQL 表。我需要对行背景进行颜色编码。所以我为 DataRow 设置了一个样式:

     <DataGrid.RowStyle>
                <Style TargetType="DataGridRow">
                    <Setter Property="Background">
                        <Setter.Value>
                            <MultiBinding Converter="{StaticResource rowColor}">
// here I'm passing DataRowView that gives me access to row data - this is working well
                                <Binding /> 
// below part is not working (compiling, but passing nothing)
                                <Binding Source="{RelativeSource Mode=Self}" Path="IsSelected" /> 
                            </MultiBinding>
                        </Setter.Value>
                    </Setter>
                </Style>
            </DataGrid.RowStyle>

事情是我需要根据行的数据设置许多颜色。即绿色、黄色、红色......这是为了立即视觉识别每个项目的状态。这部分工作完美。

但是我还需要对每一行进行颜色编码,当它处于选定状态时。否则,一旦选择,它们都将具有无用的默认 RoyalBlue 背景。所以对于选定的行,我需要设置 DarkGreen、DarkYellow、DarkRed... 等。因此,MultiBinding 和我尝试将自己的 IsSelected 属性传递给转换器。那是行不通的。无论我尝试了什么(我尝试了很多,还有其他属性),在我的 Convert() 函数中,values[0] 都可以(DataRowView),但 values[1] 始终是一个 DependencyObject.Unset。

这样做的正确方法是什么?

标签: c#wpfdatagrid

解决方案


尝试设置RelativeSource属性而不是Source

<Binding RelativeSource="{RelativeSource Self}" Path="IsSelected" />

推荐阅读