显示图片
问题描述:
我想显示存储在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}}"/>
...但是当您设置你的列表框绑定到列表中,你只是选择图象 - 属性到一个列表:
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;
编辑新增的ToArray的()调用到L inq查询来反映Prashant的发现。
感谢马特,但这两个解决方案都不适合我:( – 2009-04-20 09:40:10
嗯。好的...你有没有尝试在你的Convert方法中添加一个断点并检查它是否被打中,并且“if”语句成功? – 2009-04-20 09:45:41
马特,你的建议后,一些小的修改,谢谢很多:) – 2009-04-20 09:53:30