c# - Windows Phone 8 - 使用 Binding 将 byte[] 数组加载到 XAML 图像中

标签 c# wpf windows xaml windows-phone-8

我将图像存储为 byte[] 数组,因为我无法将它们存储为 BitmapImage。 ShotItem 类将存储在 observableCollection 中的 IsolatedStorage 中。

namespace MyProject.Model
{
    public class ShotItem : INotifyPropertyChanged, INotifyPropertyChanging
    {
        private byte[] _shotImageSource;
        public byte[] ShotImageSource
        {
            get
            {
                return _shotImageSource;
            }
            set
            {
                NotifyPropertyChanging("ShotImageSource");

                _shotImageSource = value;
                NotifyPropertyChanged("ShotImageSource");
            }
        }
        ...
    }
}

在我的 xaml 文件中,我有以下内容:

<Image Source="{Binding ShotImageSource}" Width="210" Height="158" Margin="12,0,235,0" VerticalAlignment="Top" />

不幸的是,我无法将图像作为字节直接加载到 xaml 中的图像容器中。我不知何故需要将 ShotImageSource byte[] 转换为 BitmapImage。我正在加载很多图像,所以这是否也必须异步完成。

我尝试使用转换器绑定(bind),但我不确定如何让它工作。任何帮助将不胜感激:)。

最佳答案

这是一个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();
    }
}

关于c# - Windows Phone 8 - 使用 Binding 将 byte[] 数组加载到 XAML 图像中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19259469/

相关文章:

c# - 如何将 TabControl 绑定(bind)到 ViewModel 集合?

c# - '[未知 ]' property does not point to a DependencyObject in path ' (0).(1)[3].(2)'

c# - 如何在轮盘赌中将球停在特定数字

python-3.x - Anaconda/Orange3 产生 OSError : [WinError 193] %1 is not a valid Win32 application

c# - 在 asp.net gridview 中更改选定行的颜色

c# - 如何获取 OdbcDataReader 返回的字段列表?

c# - 将文件保存到 Azure Functions 中的临时位置

c# - 当应用程序未获得焦点时监听键

c++ - 当我从剪贴板粘贴到外部程序时,为什么 Qt 程序会处理剪贴板数据?

windows - 如何在cmd文件中隐藏Windows中的密码字符