繁体   English   中英

在 WPF 列表框中显示图像

[英]Show Images in WPF ListBox

我试图将存储在 MSSql Db 中的图像显示为 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.");
        }
    }

我会尝试一下。

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;

编辑向 linq 查询添加了 ToArray() 调用以反映 Prashant 的发现。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM