【问题标题】:WPF DataGrid bind cell background color to property of assigned Data objectWPF DataGrid 将单元格背景颜色绑定到分配的 Data 对象的属性
【发布时间】:2013-05-13 17:13:30
【问题描述】:

我有一个 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>

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

【问题讨论】:

  • 你试过Value="{Binding BackgroundColor}"吗?
  • 这似乎奏效了,只需要弄清楚显示的小空白填充而不是完整的背景填充。
  • 知道了,必须将单元格的边框厚度设置为 0。如果您想让您的评论成为答案,我会将其标记为正确。
  • 我已经发布了我的评论作为答案。谢谢。

标签: c# wpf binding datagrid


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-26
    • 2013-12-27
    • 1970-01-01
    • 2011-12-12
    • 2013-04-21
    • 2011-04-03
    • 2017-10-04
    相关资源
    最近更新 更多