【问题标题】:Show Image in dynamically generated DataGrid.Columns in WPF在 WPF 中动态生成的 DataGrid.Columns 中显示图像
【发布时间】:2019-12-17 18:19:11
【问题描述】:

我必须从查询中转换信息数据,并根据从底层数据库读取的值显示图像。

假设我的查询中有这些数据:

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

还有这个:

而我就是不明白。我知道我已经接近了,但我猜还是错过了显而易见的事情。

【问题讨论】:

  • 还有一个类似的问题:stackoverflow.com/q/40358111/1506454
  • @ASh 这很有帮助!实际上只需要弄清楚如何让我的转换器从行中读取警报级别,以便分配正确的图像。比我第一次简单得多。我想我会更新我的代码示例以反映这些变化。

标签: c# wpf datagrid


【解决方案1】:

您可以处理AutoGeneratingColumn 事件并以编程方式创建一个包含Image 元素的DataGridTemplateColumn。试试这个:

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

【讨论】:

  • 我是否需要对图像文件做一些特别的事情,或者只是让它们作为内容/复制总是可以的?因为我提供了图像文件的相对路径,如我的屏幕截图所示,并且当我使用提供的代码示例时,它不会显示任何图像或值。就像单元格是空的。我必须在下周五之前提供这个功能,从上周日开始我就一直在努力。越来越紧张......
  • 此外,当使用 XAML DataTemplate 中的 IValueConverter 作为 DataGrid.Resources 时,我的转换器被调用,但它似乎没有像我预期的那样工作,即对象值参数是整行以 DataRowView 的形式,而不仅仅是一个单元格值。所以几乎不可能解决。我现在真的走投无路了。非常感谢您的帮助。
  • 你是如何使用转换器的?你不应该需要一个。
  • @WillMarcouiller:正如我所料,您的图片路径无效。将“images”替换为“../images”即可,例如:"../images/circle_grey.ico".
  • 你绝对让我开心!我最诚挚的感谢您的支持! +1 并接受答案。 :)
猜你喜欢
  • 2011-11-01
  • 1970-01-01
  • 2016-12-30
  • 1970-01-01
  • 1970-01-01
  • 2021-04-15
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
相关资源
最近更新 更多