在Datagrid中添加图像

时间:2013-01-17 11:26:52

标签: c# wpf datagrid

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

这就是我的尝试:

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用作数据网格的Itemsource ...........如何使图像显示在数据网格列中?

3 个答案:

答案 0 :(得分:2)

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

由于您使用的是字典,请绑定,例如:

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

答案 1 :(得分:0)

我认为您的Column数据类型与itemsource数据类型不匹配。您必须为Grid Column和itemsource创建相同的数据类型Image。 在我的WPF项目中,我使用Images:

制作了我的列数据模板
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;

希望这个帮助

答案 2 :(得分:0)

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

之后在DataGrid绑定事件中尝试以下编码。在这里,我添加了图像徽标...

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;
        }
相关问题