首页 > 解决方案 > 在 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 自己自动生成列,我还尝试将它们添加到这个问题的已接受答案后面的代码中:

还有这个:

而我就是无法理解。我知道我已经很接近了,但我猜仍然缺少明显的东西。

标签: c#wpfdatagrid

解决方案


您可以处理该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
        };
    }
}

推荐阅读