Show Image in dynamically generated DataGrid.Columns in WPF

我怕爱的太早我们不能终老 提交于 2020-01-11 10:27:50

问题


I've to pivot information data from a query, and show images based on value read from the underlying database.

Let's say I have this data out of my query:

Identifiant|ProcessId|AlarmLevel
  BOUDA25  |   100   |    1
  BOUDA25  |   110   |    1
  BOUDA25  |   130   |    1
  BOUDA25  |   205   |    2
  BOUDA25  |   210   |    2

I now want to make the following WPF DataGrid display the actual images represented by images/circle_orange.ico, etc.

So far my code resembles this:

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();
}

Now I'm stuck since three days to make those image display through an ImageSource binding.

I tried to let the DataGrid autogenerate the columns by itself, and I also tried by adding them in the code behind from the accepted answer of this question:

  • How do I show image in wpf datagrid column programmatically?

And this one also:

  • WPF add datagrid image column possible?

And I just can't get it. I know I'm close, but still missing the obvious, I guess.


回答1:


You could handle the AutoGeneratingColumn event and programmatically create a DataGridTemplateColumn that contains an Image element. Try this:

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
        };
    }
}


来源:https://stackoverflow.com/questions/59379995/show-image-in-dynamically-generated-datagrid-columns-in-wpf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!