我试图在图像控件中绑定byte [],但转换器中存在一些问题。请让我知道如何解决这个问题?
我在第stream.WriteAsync(bytesArray.AsBuffer());
行收到错误,因为byte []中没有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>
答案 0 :(得分:2)
我可以通过创建如下所示的转换器来解决问题。以下是有效的。如果我能改进它,请告诉我。
代码: BitmapImage图像;
/// <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);
}