c# - 根据具体对象的 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;
任何帮助,将不胜感激。我知道以前有人问过这个问题,但是这些答案对我不起作用。我肯定错过了什么。
解决方案
您的问题来自这样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) });
推荐阅读
- android - 如何在 Android 上禁用热键/快捷方式?
- flutter - 如何在 MyApp 的 build 方法中调用 Stateless 小部件,其状态由其 Stateful Parent 管理
- python - 我正在尝试为mimic2 预处理数据集,但我被正式卡住了。新手提醒
- c# - 在 GetAuthenticationStateAsync 之外设置声明不会影响
标签 - database - 在微服务中初始化和迁移 Postgresql 模式的最佳方法
- python - Python列表与数组,如果我们知道第一个元素的位置,如何计算内存中的位置
- android - Android Studio:java 和 javax 导入的未解决参考,但项目编译
- sql - 在 Bigquery 中使用 JOIN 进行计数
- google-chrome - 无法在 Google Chrome Linux 中更改权限
- docker - 如何在 Docker 中运行 Hadoop DFSIO MapReduce 基准测试?