在WPF ListBox中显示图片

3
我正在尝试显示存储在MSSql数据库中的varbinary格式的图像,但当我执行我的代码时,它就会卡住。

代码如下...

XAML

<Window x:Class="ImageList.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:ImageList"
    Title="Window1" Height="331" Width="575">
    <Window.Resources>
        <local:BinaryImageConverter x:Key="imgConverter" />
    </Window.Resources>
    <StackPanel>
        <ListBox Name="lstImages" ItemsSource="{Binding}" >
            <ListBox.Resources>
                <DataTemplate x:Key="data">
                    <Image Source="{Binding Path=ImageData, Converter={StaticResource imgConverter}}"/>
                </DataTemplate>
            </ListBox.Resources>
        </ListBox>        
        <Button  Height="25" Name="button1" Click="button1_Click">Button</Button>
        <Button  Height="25" Name="button2" Click="button2_Click">Load Images</Button>
    </StackPanel>
</Window>

C#

{
       private void button2_Click(object sender, RoutedEventArgs e)
        {
            ImageDataContext db = new ImageDataContext();
            var data = db.ImageDetails.Select(p => p.ImageData).ToList();
            lstImages.ItemsSource = data;
        }

    }

    public class BinaryImageConverter : IValueConverter
    {
        object IValueConverter.Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value != null && value is byte[])
            {
                byte[] ByteArray = value as byte[];
                BitmapImage bmp = new BitmapImage();
                bmp.BeginInit();
                bmp.StreamSource = new MemoryStream(ByteArray);
                bmp.EndInit();
                return bmp;
            }
            return null;
        }

        object IValueConverter.ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new Exception("The method or operation is not implemented.");
        }
    }
1个回答

3
我来尝试翻译一下。

我会尝试解答这个问题。

你的 ListBox 中的每个项目都绑定到一个名为“ImageData”的属性:

<Image Source="{Binding Path=ImageData, Converter={StaticResource imgConverter}}"/>

... 但是当您设置要绑定到ListBox的列表时,您只需将ImageData属性选择到列表中:

var data = db.ImageDetails.Select(p => p.ImageData).ToList();
lstImages.ItemsSource = data;

这里最终会得到一个List<byte[]>或其他类似的东西,而不是一个带有ImageData属性的对象列表。
如果我猜得没错,你有两个选择: 1.将绑定更改为直接绑定到图像:
<Image Source="{Binding Converter={StaticResource imgConverter}}"/>

2. 更改linq查询以创建带有ImageData属性的对象:

var data = db.ImageDetails.Select(p => new { ImageData = p.ImageData.ToArray() }).ToList();
lstImages.ItemsSource = data;

编辑:根据Prashant的发现,在linq查询中添加了ToArray()调用。


嗯。好的...你尝试给你的Convert方法添加一个断点并检查它是否被触发,以及"if"语句是否成功了吗? - Matt Hamilton
嘿,Matt,你的建议经过一些小修改后起作用了,非常感谢 :) - Prashant Cholachagudda

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接