WPF将DataGridTextColumn的背景颜色按行按颜色绑定

use*_*285 2 c# data-binding wpf datagrid background-color

假设我有一个包含以下数据的DataGrid:

John, Male
Mary, Female
Tony, Male
Sally, Female
Run Code Online (Sandbox Code Playgroud)

网格绑定到Person模型对象的ObservableCollection,该对象为属性Person.Name和Person.Gender实现INofifyPropertyChanged.我现在想要将DataGridTextColumn的背景颜色绑定到人的性别,以便包含男性的行是蓝色,包含女性的行是粉红色.是否可以通过向Person模型添加另一个属性来执行此操作,如下所示:

public class Person
{
    public Color BackgroundColor
    {
        get
        {
            if (gender == "Male")
            {
                return Color.Blue;
            }
            else
            {
                return Color.Pink;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

如果是这样,我如何将其绑定到行或列的背景颜色?我已经有这样的有界列:

<DataGridColumn Header="Name" Binding={Binding Name} />
<DataGridColumn Header="Gender" Binding={Binding Gender} />
Run Code Online (Sandbox Code Playgroud)

dko*_*ozl 6

假设它BackgroundColor是一种System.Windows.Media.Color类型,而不是System.Drawing.Color,如果你想改变整行的背景,你可以改变属性DataGrid.RowStyle并将Background属性绑定到BackgroundColor属性

<DataGrid ...>
    <DataGrid.RowStyle>
        <Style TargetType="{x:Type DataGridRow}">
            <Setter Property="Background">
                <Setter.Value>
                    <SolidColorBrush Color="{Binding Path=BackgroundColor}"/>
                </Setter.Value>
            </Setter>
        </Style>
    </DataGrid.RowStyle>
</DataGrid>
Run Code Online (Sandbox Code Playgroud)