在 DataGridTemplateColumn 中添加图像 [英] Add a Image in the DataGridTemplateColumn

查看:22
本文介绍了在 DataGridTemplateColumn 中添加图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

BitmapImage im = new BitmapImage();

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

im.UriSource=new Uri(path1);


DataGridTemplateColumn one = new DataGridTemplateColumn();

this.dataGrid1.Columns.Add(one);

现在我必须在 datagridTemplateColumn 中添加 BitmapImage im.

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

如何在列中添加图片??

How to add Image in the column??

推荐答案

在代码中使用控件模板很困难.在 WPF 中,标准且有效的方法是在 XAML 中创建模板布局.然后,如果您需要将任何数据传递给您的控件,请使用数据绑定.除极少数情况外,您通常不需要在代码中构建模板.

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.

要使用您编写的 XAML 获得与上面预期相同的效果:

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

这篇关于在 DataGridTemplateColumn 中添加图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆