wpf 在 DataGridTemplateColumn 中添加图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14432313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 07:07:51  来源:igfitidea点击:

Add a Image in the DataGridTemplateColumn

wpfdatagriddatagridtemplatecolumn

提问by Raghu

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.

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

How to add Image in the column??

如何在列中添加图像?

回答by Mohammad

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.

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

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

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

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