DataGrid 显示图像的路径而不是图像本身 [英] DataGrid shows path of image instead of image itself

查看:21
本文介绍了DataGrid 显示图像的路径而不是图像本身的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下几行最终显示了路径而不是它指向的图像.AutoGenerateColums 设置为 true,将其设置为 false 将在完全空行中结束.

The following lines end up showing the path instead of the image it leads to. The AutoGenerateColums is set to true, setting it to false will end up in totally empty lines.

System.Data.DataTable DataTable = new System.Data.DataTable();
System.Data.DataColumn DataColumn = new System.Data.DataColumn();

Uri uri = new Uri(@"C:/Users/User/Desktop/szagdoga/error.png");
BitmapImage img = new BitmapImage(uri);
DataColumn.DataType = img.GetType();
DataColumn.ColumnName = ("this");

DataTable.Columns.Add("Test #");
DataTable.Columns.Add(DataColumn);
DataTable.Columns.Add("Min Range");
DataTable.Columns.Add("Max Range");
DataTable.Columns.Add("Result");
for (int i = 6; i <50; i++)
    DataTable.Rows.Add(ExcelFile[0, i],img, ExcelFile[1,i],0,0,0);

ChannelDataGrid.ItemsSource = DataTable.DefaultView;

请帮我以某种方式显示图像!谢谢.

Please help me somehow show the images! Thank you.

推荐答案

首先,DataGrid 默认生成 DataGridTextColumns,我们必须使用 AutoGeneratingColumn 事件来改变列的类型.我们需要在模板中使用包含图像的 DataGridTemplateColumn(图像源应该绑定到正确的 DataTable 列).定义模板的最佳位置是在资源中.

first of all, DataGrid generate DataGridTextColumns by default and we have to use AutoGeneratingColumn event to change type of column. We need to use DataGridTemplateColumn which contains Image in template (image source should be bound to correct DataTable column). The best place to define template is in Resources.

解决问题的方法如下:

xml 部分

<DataGrid Name="ChannelDataGrid" AutoGeneratingColumn="ChannelDataGrid_OnAutoGeneratingColumn">

    <DataGrid.Resources>
        <DataTemplate x:Key="ImgCell">
            <Image Source="{Binding Path=Img}"/>
        </DataTemplate>
    </DataGrid.Resources>        
</DataGrid>

代码:

private void InitializeDataTable()
{
    System.Data.DataTable DataTable = new System.Data.DataTable
    {
        Columns = {"Test #", "Img", "Min Range", "Max Range", "Result"}
    };

    Uri uri = new Uri(@"C:/Users/User/Desktop/szagdoga/error.png");

    for (int i = 6; i < 50; i++)
        DataTable.Rows.Add(ExcelFile[0, i], uri, ExcelFile[1, i], 0, 0);

    ChannelDataGrid.ItemsSource = DataTable.DefaultView;
}

private void ChannelDataGrid_OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    if (e.PropertyName == "Img")
    {
        // replace text column with image column
        e.Column = new DataGridTemplateColumn
        {
            // searching for predefined tenplate in Resources
            CellTemplate = (sender as DataGrid).Resources["ImgCell"] as DataTemplate,
            HeaderTemplate = e.Column.HeaderTemplate,
            Header = e.Column.Header
        };
    }
}

这篇关于DataGrid 显示图像的路径而不是图像本身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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