【问题标题】:Adding Image in Datagrid在 Datagrid 中添加图像
【发布时间】:2013-01-17 11:26:51
【问题描述】:

这是我的数据网格,我想在网格列中显示图像,但它向我显示文本 System.Windows.Media.Imaging.BitmapImage,而不是显示图像。 如何在数据网格列中添加图像?

这是我尝试过的:

Dictionary dict1=new Dictionary < string,object>();

string keyimage="Image";

object a1 = new BitmapImage();

a1=Imaging.CreateBitmapSourceFromHIcon(SystemIcons.Information.Handle, Int32Rect.Empty, null);

dict1.Add(keyimage, a1);

这个dict1 充当datagrid 的Itemsource............如何使图像显示在datagrid 列中?

【问题讨论】:

  • 您使用什么列类型来显示图像?
  • 这是我的问题............我应该使用什么列类型来显示图像?
  • 这本词典里有什么,只有图像?
  • 不只是图像。我只想在 c# 代码中的 datagrid 中添加一个 Image 列,而不是在 xaml 中

标签: c# wpf datagrid


【解决方案1】:

确保您使用DataGridTemplateColumn 并将图像放入其中。

由于您使用的是字典,因此绑定 ,类似于:

<Image Binding="{Binding Height="25" Width="50" Source="{Binding Value}" />

【讨论】:

    【解决方案2】:

    我想您的 Column 数据类型与 itemsource 数据类型不匹配。您必须为 Grid Column 和 itemsource 创建相同的数据类型 Image。 在我的 WPF 项目中,我使用图像制作了列数据模板:

    DataTable dtab = new DataTable();
    dtab.Columns.Add("imageColumn", typeof(BitmapImage)); 
    //Uploading dtab with Images from DataBase
    
    FrameworkElementFactory factory = new FrameworkElementFactory(typeof(Image));
    Binding bind = new System.Windows.Data.Binding("imageColumn");
    factory.SetValue(Image.SourceProperty, bind);
    DataTemplate cellTemplate = new DataTemplate() { VisualTree = factory };
    DataGridTemplateColumn imgCol = new DataGridTemplateColumn() 
    {
      Header="image",
      CellTemplate = cellTemplate
    };
    DataGrid dg = new DataGrid();
    dg.Columns.Add(imgCol);
    dg.ItemsSource = dtab.DefaultView;
    

    希望有帮助

    【讨论】:

      【解决方案3】:

      将任何图像添加到您的 Project on Resource 文件夹

      然后在 DataGrid Bind 事件中尝试以下编码。在这里我添加了图像标志...

      DataGridViewImageColumn imageColoumn = new DataGridViewImageColumn();
              imageColoumn.HeaderText = "Img";
              imageColoumn.Image = null;
              imageColoumn.Name = "DataPic";
              imageColoumn.Width = 150;
              dataGridView1.Columns.Add(imageColoumn);
      
              foreach (DataGridViewRow row in dataGridView1.Rows)
              {
                  DataGridViewImageCell cell = row.Cells[1] as DataGridViewImageCell;
                  cell.Value = (System.Drawing.Image)Properties.Resources.logo;
              }
      

      【讨论】:

      • DataGridViewImageColumn 它有任何命名空间或其他东西,而且我使用的是 wpf datagrid 而不是 datagridview
      • 好的,那你试试这个链接....stackoverflow.com/questions/7938779/…...
      • 我已经设置了 AutoGenerateColumns="True" 因为我有一个非常好的数据集,我可以很容易地将它与数据网格绑定,但现在我试图在数据集中添加一个数据集没有显示的图像...... xaml 没有变化,我唯一能做的就是在 c# 代码中做一些事情............
      猜你喜欢
      • 2011-07-05
      • 1970-01-01
      • 1970-01-01
      • 2013-03-18
      • 1970-01-01
      • 2013-11-11
      • 1970-01-01
      • 1970-01-01
      • 2023-02-08
      相关资源
      最近更新 更多