WPF DataGrid 将单元格背景颜色绑定到分配的 Data 对象的属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16527525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 08:47:01  来源:igfitidea点击:

WPF DataGrid bind cell background color to property of assigned Data object

c#wpfbindingdatagrid

提问by user2371475

I've got a DataGrid where the cells are assigned to a custom class defined below:

我有一个 DataGrid,其中单元格被分配给下面定义的自定义类:

public class DataGridVariableWrapper : DependencyObject
{
    public Variable TheVariable { get; set; }

    public Brush BackgroundColor
    {
        get { return (Brush)GetValue( BackgroundColorProperty ); }
        set { SetValue( BackgroundColorProperty, value ); }
    }
    public static readonly DependencyProperty BackgroundColorProperty = DependencyProperty.Register( "BackgroundColor", typeof( Brush ), typeof( DataGridVariableWrapper ), new UIPropertyMetadata( null ) );

    public DataGridVariableWrapper( Brush backgroundBrush, Variable theVariable )
    {
        this.BackgroundColor = backgroundBrush;
        this.TheVariable = theVariable;
    }

    public override string ToString()
    {
        return TheVariable.Value.ToString();
    }

}

I'm trying to have the DataGridCell background bound to the BackgroundColor property of this data wrapper class. I've tried:

我正在尝试将 DataGridCell 背景绑定到此数据包装器类的 BackgroundColor 属性。我试过了:

<DataGrid.CellStyle>
    <Style TargetType="DataGridCell">
        <Setter Property="Background" Value="{Binding DataGridVariableWrapper.BackgroundColor}" />
    </Style>
</DataGrid.CellStyle>

But the background color remains unchanged. Am I doing something wrong here?

但背景颜色保持不变。我在这里做错了吗?

回答by LPL

If a data object is assigned to a DataGridCellyou will find it in the DataContext. That's why all you have to do in binding is to specify the desired property.

如果将数据对象分配给 a,DataGridCell您将在DataContext. 这就是为什么您在绑定中所要做的就是指定所需的属性。

<Style TargetType="DataGridCell">
    <Setter Property="Background" Value="{Binding BackgroundColor}" />
</Style>