【问题标题】:How to display BitmapImage correctly?如何正确显示 BitmapImage?
【发布时间】:2015-01-28 15:40:41
【问题描述】:

我想在 ListBox 中显示来自 SQL Server 数据库的一些图像。我将图像从二进制转换为BitmapImage,然后添加如下:

foreach (var screenshot in screenshots)
{
    ImageListBox.Items.Add(screenshot);
}

输出如下:

如何正确显示图片?

编辑:这是我的 xaml 代码:

<ListBox Name="ImageListBox">
</ListBox>

编辑 2:

这就是我转换图像的方式:

public BitmapImage ConvertImage(byte[] value)
{
    if (value != null && value.Length > 0)
    {
        using (MemoryStream stream = new MemoryStream(value))
        {
            BitmapImage image = new BitmapImage();
            image.BeginInit();
            image.StreamSource = stream;
            image.EndInit();
            return image;
        }
    }
    return null;
}

这是我的查询:

var screenshots = context
    .Error.Include(_ => _.ErrorScreenshots)
    .First(_ => _.Id == selectedError.Id)
    .Error
    .Select(_ => new { Image = ConvertImage(_.Screenshot) })
    .ToArray();

【问题讨论】:

  • 了解data templates(见msdn)。
  • 我是否理解正确:ListBox 默认调用 toString(),这就是为什么它看起来很奇怪?

标签: c# .net sql-server wpf listbox


【解决方案1】:

ListBox 将默认使用其 toString() 方法显示对象。在您的情况下,您最终会得到“Image = System.Windows.Media.Bitmap.Image”

为了指示每个项目应显示为 Image 对象,请指定 ItemTemplate。

<ListBox Name="ImageListBox">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <StackPanel Orientation="Horizontal" >
        <Image Source="{Binding}" />
      </StackPanel>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

【讨论】:

  • 我的源代码有些问题。图片来自数据库,我不知道应该指定什么来源。
  • 我更新了答案。我认为在您的情况下,由于您使用的是 BitmapImage 对象,因此您可以直接绑定到该对象,而不是绑定到 ImageSource。 A BitmapImage 是一个 ImageSource 所以应该可以工作。
  • 图像是否可能为空/空? link
  • @J.Doe 创建位图图像时,您肯定做错了什么。您也应该发布该代码。
  • 也许,如果您的转换无效。我测试了解决方案,将两个不同的 BitmapImage 对象添加到 ListBox.Items。我从本地文件创建的一个位图图像,另一个我从二进制数据创建的。两者都在 ListBox 中显示得很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多