c# - 在 WPF 中动态生成的 DataGrid.Columns 中显示图像
问题描述
我必须从查询中转换信息数据,并根据从底层数据库读取的值显示图像。
假设我的查询中有这些数据:
Identifiant|ProcessId|AlarmLevel
BOUDA25 | 100 | 1
BOUDA25 | 110 | 1
BOUDA25 | 130 | 1
BOUDA25 | 205 | 2
BOUDA25 | 210 | 2
我现在想让以下 WPF DataGrid 显示由images/circle_orange.ico
等
表示的实际图像。
到目前为止,我的代码类似于:
private void PopulateGrid(IEnumerable<AlarmeViewModel> alarmes) {
// Used to pivot the information data
var table=new DataTable();
// Generates the columns based on rows
table.Columns.Add("Identifiant");
table.Columns.Add("=>");
alarmes.ForEach(a => a.Processes.ForEach(pid => table.Columns.Add(columnName:pid, type typeof(string))));
// Generates the rows
var images = new string[] {
"images/circle_grey.ico",
"images/circle_orange.ico",
"images/circle_yellow.ico",
"images/circle_red.ico",
"images/circle_green.ico"
};
alarmes.ForEach(a => {
var row = table.NewRow();
row[0] = a.Identifiant
for(int i=0; i<a.Niveaux.Count; row[a.Processes[i]]=images[a.AlarmLevel[1]], i++);
table.Rows.Add(row);
});
// Refreshes the DataGrid content
alarmDataGrid.BeginInit();
alarm.DataGrid.ItemsSource=table.DefaultView;
alarmDataGrid.EndInit();
}
现在我被困三天以来通过 ImageSource 绑定显示这些图像。
我试图让 DataGrid 自己自动生成列,我还尝试将它们添加到这个问题的已接受答案后面的代码中:
还有这个:
而我就是无法理解。我知道我已经很接近了,但我猜仍然缺少明显的东西。
解决方案
您可以处理该AutoGeneratingColumn
事件并以编程方式创建一个DataGridTemplateColumn
包含Image
元素的事件。尝试这个:
private void OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.PropertyName != "Identifiant" && e.PropertyName != "=>")
{
FrameworkElementFactory image = new FrameworkElementFactory(typeof(Image));
image.SetBinding(Image.SourceProperty, new Binding(e.PropertyName));
e.Column = new DataGridTemplateColumn
{
CellTemplate = new DataTemplate() { VisualTree = image },
Header = e.PropertyName
};
}
}
推荐阅读
- opengl - 投影矩阵:深度映射到什么?
- spring - 使用 Unroll 时 Spring-Boot 和 Spock 失败
- selenium - Azure Pipelines (DevOps) Selenium 自动化浏览器在内存中无头运行导致错误
- tomcat - 来自命令行的错误,但使用 URL 从网页成功执行了 A SERVLET。谢谢
- swift - 如何处理 500 个 http 错误
- java - Java mapToInt vs Reduce with map
- javascript - 每秒单击一次按钮,直到
- python - 字典值(不是键)的内置“all()”函数
- mysql - SQL IS NULL 检查未给出正确结果
- node.js - node.js 中用于数据库插入的 Redis 队列