wpf Windows Phone 8 - 使用绑定将字节 [] 数组加载到 XAML 图像中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19259469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Windows Phone 8 - Load byte[] array into XAML image with Binding
提问by Seb123
I am storing images as byte[] arrays because I can't store them as BitmapImage. The ShotItem class will be stored in IsolatedStorage in an observableCollection.
我将图像存储为 byte[] 数组,因为我无法将它们存储为 BitmapImage。ShotItem 类将存储在 IsolatedStorage 中的 observableCollection 中。
namespace MyProject.Model
{
public class ShotItem : INotifyPropertyChanged, INotifyPropertyChanging
{
private byte[] _shotImageSource;
public byte[] ShotImageSource
{
get
{
return _shotImageSource;
}
set
{
NotifyPropertyChanging("ShotImageSource");
_shotImageSource = value;
NotifyPropertyChanged("ShotImageSource");
}
}
...
}
}
In my xaml file I have the following:
在我的 xaml 文件中,我有以下内容:
<Image Source="{Binding ShotImageSource}" Width="210" Height="158" Margin="12,0,235,0" VerticalAlignment="Top" />
Unfortunately I can't load the image as a byte straight into the Image container in the xaml. I somehow need to convert the ShotImageSource byte[] to BitmapImage. I am loading quite a few images so would this have to also be done asynchronously.
不幸的是,我无法将图像作为一个字节直接加载到 xaml 中的图像容器中。我不知何故需要将 ShotImageSource byte[] 转换为 BitmapImage。我正在加载相当多的图像,所以这也必须异步完成。
I tried to use a converter binding, but I wasn't sure on how to get it to work. Any help would be greatly appreciated :).
我尝试使用转换器绑定,但我不确定如何让它工作。任何帮助将不胜感激 :)。
回答by Olivier Payen
Here is the code for a Converterthat will convert your byte[]into a BitmapImage:
下面是一个代码Converter,将您转换byte[]成BitmapImage:
public class BytesToImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value != null && value is byte[])
{
byte[] bytes = value as byte[];
MemoryStream stream = new MemoryStream(bytes);
BitmapImage image = new BitmapImage();
image.SetSource(stream);
return image;
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}

