2
我想顯示存儲在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.");
}
}
感謝馬特,但這兩個解決方案都不適合我:( – 2009-04-20 09:40:10
嗯。好的...你有沒有嘗試在你的Convert方法中添加一個斷點並檢查它是否被打中,並且「if」語句成功? – 2009-04-20 09:45:41
馬特,你的建議後,一些小的修改,謝謝很多:) – 2009-04-20 09:53:30