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

时间:2015-10-23 18:38:24

标签: c# wpf data-binding datagrid background-color

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

John, Male
Mary, Female
Tony, Male
Sally, Female

网格绑定到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;
            }
        }
    }

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

<DataGridColumn Header="Name" Binding={Binding Name} />
<DataGridColumn Header="Gender" Binding={Binding Gender} />

3 个答案:

答案 0 :(得分:6)

假设BackgroundColor属于System.Windows.Media.Color类型,而不是System.Drawing.Color,如果您想要更改整行的背景,可以更改DataGrid.RowStyle并绑定{{ 1}}属性Background属性

BackgroundColor

答案 1 :(得分:1)

您希望实现IValueConverter将String转换为Brush。见http://www.wpf-tutorial.com/data-binding/value-conversion-with-ivalueconverter/

public class StringToBrushConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var val = (string)value;
        return new SolidColorBrush(val == "male" ? Colors.Blue : Colors.Pink);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

在XAML中,您希望<Window.Resources>喜欢

<Window.Resources>
    <local:StringToBrushConverter x:Key="stringToBrush" />
    <Style x:Key="MaleFemaleStyle" TargetType="DataGridCell">
        <Setter Property="Background" Value="{Binding Path=Gender, Converter={StaticResource stringToBrush}}" />
    </Style>
</Window.Resources>

然后将MaleFemaleStyle应用于你的网格。

<DataGrid CellStyle="{StaticResource MaleFemaleStyle}">
    ...
</DataGrid>

答案 2 :(得分:0)

这对我有用

Node 4.2.1