【问题标题】:WPF DataGrid cell background using bindingWPF DataGrid 单元格背景使用绑定
【发布时间】:2011-12-12 15:47:24
【问题描述】:

我有一个名为 Color 的列的 DataGrid。

<DataGridTextColumn Header="Color" Binding="{Binding MyColor.Percentage}"/>

DataGrid 的 ItemSource 是一个带有MyColor 属性的对象。

public class MyColor
{
    Color Background { get; set; }
    int Percentage { get; set; }
}

当设置 ItemSource 时,列自动填充 Percentage 的值。现在我想将此列中每个单元格的背景设置为与MyColor.Color 属性对应的颜色。有没有办法使用绑定来做到这一点?类似的东西

Background="{Binding MyColor.Color}"

Color属性是html格式#XXXXXXXX(是不是叫html格式?)。

【问题讨论】:

    标签: wpf binding datagrid colors background


    【解决方案1】:

    您可以通过CellStyle进行设置:

    <DataGridTextColumn Header="Color" Binding="{Binding MyColor.Percentage}">
        <DataGridTextColumn.CellStyle>
            <Style TargetType="DataGridCell">
                <Setter Property="Background" Value="{Binding MyColor.Background}" />
            </Style>
        </DataGridTextColumn.CellStyle>
    </DataGridTextColumn>
    

    您还必须更改您的 MyColor 类以具有类型为 BrushBackground 属性,而不是 Color。或者您可以使用转换器将Color 转换为SolidColorBrush

    【讨论】:

    • 好的,我管理将输入转换为 SolidColorBrush,但出现了问题。由于我的应用程序的其余部分,我使用 Dispatcher 将 ItemSource 分配给 DataGrid,当我将您的 XAML 代码添加到我的时,它会弹出错误“必须在与 DependencyObject 相同的线程上创建 DependencySource”
    猜你喜欢
    • 2017-10-04
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-26
    • 2016-08-02
    相关资源
    最近更新 更多