【问题标题】:Display image from Database on WPF DataGrid在 WPF DataGrid 上显示来自数据库的图像
【发布时间】:2016-04-28 23:44:35
【问题描述】:

我想在数据库中的DataGrid 中显示图像,我正在使用 WPF

[

我可以检索图像名称,如您在图像列中看到的那样,但我无法显示它。

<DataGrid.Columns>
    <DataGridTextColumn Header="ID" Binding="{Binding Path=Studentid}"/>
        <DataGridTemplateColumn Header="Picture" Width="50">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Image Stretch="Fill" Source="{Binding Images/Students/ImageColumnNameInDatabase}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
 </DataGrid.Columns>

我用于填充数据网格的 c# 代码

conn = new SqlConnection(connstring);
conn.Open();
cmd = new SqlCommand("Select * From AddStudentTb", conn);
try
{
    DataGridView dv = new DataGridView();
    SqlDataAdapter da = new SqlDataAdapter(cmd);

    da.Fill(dt);
    datagridv.ItemsSource = dt.DefaultView;
}
finally
{
    conn.Close();
}

【问题讨论】:

  • 图片从何而来?
  • 你尝试过什么?显示您的代码。
  • 请发布您的代码以展示您的努力。看起来您没有以正确的方式绑定图像。
  • 我不明白在哪里给出显示图像的相对文件夹路径,还有一个认为我正在检索 DataGrid 中的图像,但只有那些像这样保存的图像 C:\VSprojects\Images\play.png正在显示,但另一方面,我只是将名称保存在数据库中,例如 play.png 并且这些图像位于 bin>Images>Students 文件夹中

标签: c# wpf wpfdatagrid


【解决方案1】:

尝试在DataTemplate中绑定图片源,

<DataGridTemplateColumn Header="Image" Width="SizeToCells" IsReadOnly="True">
   <DataGridTemplateColumn.CellTemplate>
      <DataTemplate>
           <Image Source="{Binding Image}" />
      </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
 </DataGridTemplateColumn>

或者你可以参考this问题。

【讨论】:

  • 好的,我明白了,但我的图片保存在 bin >Images 文件夹中
  • @BilalMásInteligente:请发布您的代码。只有我才能理解真正的问题。
  • SqlDataAdapter da = new SqlDataAdapter(cmd); da.填充(dt); datagridv.ItemsSource = dt.DefaultView;
【解决方案2】:

这就是我所做的 使用像这样的图像控件在数据网格中添加数据模板

            <DataGridTemplateColumn Header="File Type" Width="*">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Image Height="25" Width="50" Source="{Binding FileIcon}"  />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>

如您所见,我正在将 Image 与一个名为“FileIcon”的属性绑定,该属性在类 Version 中使用,如下所示

            public class Version
            {
              public string FileIcon { get; set; }
            }

现在您要做的就是绑定提供“FileIcon”的路径并像这样更新DataGrid的ItemSource

            ObservableCollection<Version> items = new ObservableCollection<Version>();

            items.Add(new Version()
            {
                FileIcon = "Your Database Variable",
            });
            YourDataGrid.ItemsSource = null;
            YourDataGrid.ItemsSource = items;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-19
    • 2018-04-02
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    • 1970-01-01
    相关资源
    最近更新 更多