Add Image to DataGridTemplateColumn

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 need to add BitmapImage im to datagridTemplateColumn.

How to add an image to a column

+4


source to share


1 answer


Working with control patterns in code is tricky. In WPF, the standard and efficient way is to create a template in XAML. And then, if you need to pass any data to your controls, you use data binding. You usually don't need to create templates in your code, except in rare circumstances.

To get the same effect you listed 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 needs to be dynamic for each row of the grid, you can change 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 is some sample code to populate a 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; }
}

      

+14


source







All Articles