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

查看:728
本文介绍了在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.

如何在列中添加图像?

推荐答案

在代码中使用控件模板很难。
在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>

如果图像路径必须对每个网格行都是动态的,可以这样修改: p>

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天全站免登陆