我正在尝试将存储在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.");
}
}
答案 0 :(得分:2)
我会捅这个。
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的发现。