Add a Image in the DataGridTemplateColumn
Asked Answered
E

1

5
BitmapImage im = new BitmapImage();

string path1 = @"C:\abc.png";

im.UriSource=new Uri(path1);


DataGridTemplateColumn one = new DataGridTemplateColumn();

this.dataGrid1.Columns.Add(one);

Now i have to add the BitmapImage im in the datagridTemplateColumn.

How to add Image in the column??

Enliven answered 21/1, 2013 at 3:54 Comment(0)
S
19

Working with control templates in code is hard. In WPF the standard and effective way is to create your template layout in XAML. And then if you need to pass any data to your controls you use Data Binding. You shouldn't normally need to construct templates in code except for rare circumstances.

To get the same effect you intended above using XAML you write:

    <DataGrid x:Name="dataGrid1">
        <DataGrid.Columns>
            <DataGridTemplateColumn>
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Image Source="file:///C:\abc.png" />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>

If the image path has to be dynamic for every grid row you can modify it like this:

    <DataGrid x:Name="dataGrid1" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTemplateColumn>
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Image Source="{Binding ImageFilePath}" />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>

and here's an example code behind for populating the grid with some data:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        List<MyDataObject> list = new List<MyDataObject>();
        list.Add(new MyDataObject() { ImageFilePath = new Uri("file:///c:\\abc.png") });
        list.Add(new MyDataObject() { ImageFilePath = new Uri("file:///c:\\def.png") });
        dataGrid1.ItemsSource = list;
    }
}

public class MyDataObject
{
    public Uri ImageFilePath { get; set; }
}
Sumbawa answered 21/1, 2013 at 9:34 Comment(3)
Perfect example. I'm new to WPF and so much of still seems like magic compared to Winforms. thxLugubrious
How do I use relative path url and still be able to display images ?Weidar
You can use a ValueConverter to convert your string into an ImageSource. This SO thread shows how to do it including whether to use caching or not: https://mcmap.net/q/1921264/-wpf-memory-implications-of-using-valueconverter-to-create-bitmapimage-for-imagesourceSumbawa

© 2022 - 2024 — McMap. All rights reserved.