Windows 8 XAML将byte[]绑定到Image控件

本文关键字:绑定 Image 控件 XAML byte Windows | 更新日期: 2023-09-27 17:57:47

我正在尝试绑定图像控件中的byte[],但转换器中存在一些问题。请告诉我如何解决这个问题?我在stream.WriteAsync(bytesArray.AsBuffer());行遇到错误,因为字节[]中没有AsBuffer函数。我该怎么解决这个问题?

代码:

public object Convert(object value, Type targetType, object parameter, string language)
        {
            byte[] bytesArray;
            if (value != null && value is byte[] && (value as byte[]).Length > 0)
            {
                bytesArray = value as byte[];
            }
            else
            {
                //TODO: Add default Image here
            }
            using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
            {
                BitmapImage image = new BitmapImage();
                stream.WriteAsync(bytesArray.AsBuffer());
                stream.Seek(0);
                image.SetSource(stream);
                return image;
            }
        }

XAMl代码:

<Image Source="{Binding Path=OnlineBooksDetail[0].ImageSource, Converter={StaticResource ByteToBitmapImageConverter}}" Width="407" Height="542">
                        </Image>

Windows 8 XAML将byte[]绑定到Image控件

我可以通过创建Converter来解决这个问题,如下所述。下面的正在工作。如果我能改进的话,一定要告诉我。

代码:位图图像;

    /// <summary>
    /// Converts the specified value.
    /// </summary>
    /// <param name="value">The value.</param>
    /// <param name="targetType">Type of the target.</param>
    /// <param name="parameter">The parameter.</param>
    /// <param name="language">The language.</param>
    /// <returns></returns>
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        byte[] bytesArray = null;
        if (value != null && value is byte[] && (value as byte[]).Length > 0)
        {
            bytesArray = value as byte[];
        }
        else
        {
            //TODO: Add default Image here
        }
        using (MemoryRandomAccessStream memoryStream = new MemoryRandomAccessStream(bytesArray))
        {
            this.image = new BitmapImage();
            this.SetImageSource(memoryStream);
            return image;
        }
    }
    /// <summary>
    /// Sets the image source.
    /// </summary>
    /// <param name="memoryStream">The memory stream.</param>
    /// <exception cref="System.NotImplementedException"></exception>
    private async void SetImageSource(MemoryRandomAccessStream memoryStream)
    {
        await this.image.SetSourceAsync(memoryStream);
    }