首页 > 解决方案 > 根据具体对象的 Color 属性设置 WPF DataGridRow 背景颜色

问题描述

我已经多次看到这个问题被问过,而且似乎在每种情况下都在 xaml.xml 中设置了颜色。我已经按照我想要的方式在我的对象中映射了颜色。请看代码:

public class Alert
{
     public Color BackgroundColor { get; set; }
     public DateTime Expires { get; set; }
     public string Event { get; set; }
     public string AreaDescription { get; set; }
}

然后我有一个绑定到数据网格的警报列表。

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();


        this.Alerts.Columns.Add(new DataGridTextColumn()
        {
            Header = "Expires",
            Binding = new Binding("Expires")
        });

        this.Alerts.Columns.Add(new DataGridTextColumn()
        {
            Header = "Event",
            Binding = new Binding("Event")
        });

        this.Alerts.Columns.Add(new DataGridTextColumn()
        {
            Header = "Area Description",
            Binding = new Binding("AreaDescription")
        });

        this.Alerts.ItemsSource = new FeatureCollection().GetFeatures().GetAlerts();
    }
}

我的xml:

    <Grid>
    <DataGrid x:Name="Alerts" AutoGenerateColumns="False">
        <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
                <Setter Property="Background" Value="{Binding BackgroundColor}"/>
            </Style>
        </DataGrid.RowStyle>
    </DataGrid>
</Grid>

上面的行样式设置器不起作用。我也尝试使用数据触发器无济于事。

应该发生的是该行应该从 Alert 类中的 BackgroundColor 属性中获取其颜色。背景颜色在“new FeatureCollection().GetFeatures().GetAlerts();”这一行的那些链式方法中设置 那个代码这里没有列出,只知道颜色已经设置好了,比如 BackgroundColor = Color.Yellow;

任何帮助,将不胜感激。我知道以前有人问过这个问题,但是这些答案对我不起作用。我肯定错过了什么。

标签: c#wpfdatagrid

解决方案


您的问题来自这样BackGroundcolor一个事实,即不是Color刷子而是刷子。所以这会起作用:

public class Alert
{
    public SolidColorBrush BackgroundColor { get; set; }
    public DateTime Expires { get; set; }
    public string Event { get; set; }
    public string AreaDescription { get; set; }
}

也许是这样的:

alerts.Add(new Alert() { BackgroundColor = new SolidColorBrush(Colors.Aqua)});
alerts.Add(new Alert() { BackgroundColor = new SolidColorBrush(Colors.Black) });
alerts.Add(new Alert() { BackgroundColor = new SolidColorBrush(Colors.Blue) });
alerts.Add(new Alert() { BackgroundColor = new SolidColorBrush(Colors.Yellow) });

如果您想要更花哨的东西,可以使用以下Brush类型:

public Brush BackgroundColor { get; set; }

alerts.Add(new Alert() { BackgroundColor = new LinearGradientBrush(Colors.Black, Colors.Red, 30) });
alerts.Add(new Alert() { BackgroundColor = new SolidColorBrush(Colors.Black) });

推荐阅读