1

我有一个 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();
    }

}

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

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

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

4

1 回答 1

2

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

<Style TargetType="DataGridCell">
    <Setter Property="Background" Value="{Binding BackgroundColor}" />
</Style>
于 2013-05-13T18:19:48.750 回答