【发布时间】:2017-06-01 05:22:40
【问题描述】:
如何使用 XAML 对图像进行数据绑定?
具体来说,我有一个流对象,我想将其转换为图像。
但是,我只是找不到如何执行此操作的基本示例。
1. viewmodel 属性是什么样的?
我是否使用 ImageSource?
我需要一个值转换器吗?
2。 XAML 是什么样的?
【问题讨论】:
标签: xamarin.forms
如何使用 XAML 对图像进行数据绑定?
具体来说,我有一个流对象,我想将其转换为图像。
但是,我只是找不到如何执行此操作的基本示例。
1. viewmodel 属性是什么样的?
我是否使用 ImageSource?
我需要一个值转换器吗?
2。 XAML 是什么样的?
【问题讨论】:
标签: xamarin.forms
Forms 有一个StreamImageSource,您可以使用它来执行此操作。但是,我认为如果不编写自定义转换器就不能在 XAML 中使用它。要在代码中使用它,您可以执行以下操作:
image1.Source = ImageSource.FromStream(() =>
{
// whatever you need to do to create your stream
return stream;
});
【讨论】:
该演示通过代码说明了绑定。对于XAML 实现,您需要以下内容:-
<Image Source="{Binding MyImageAsBytes, Converter={StaticResource MyByteToImageSourceConverter}}" />
一旦您的ViewModel 中有您的byte[],您将需要一个转换器来将此包含图像的字节数组转换为Xamarin.Forms ImageSource。
转换器,采用byte[] 数组并通过以下方式转换为ImageSource:-
objImageSource = ImageSource.FromStream(() => new MemoryStream(bytImageData));
示例:-
StackLayout objStackLayout = new StackLayout();
byte[] bytImage = { your image as a byte collection }
this.BindingContext = new MyImageViewModel()
{
MyImageAsBytes = bytImage
};
Image objImage = new Image();
objImage.SetBinding(Image.SourceProperty, "MyImageAsBytes", converter: new MyByteToImageSourceConverter());
objStackLayout.Children.Add(objImage);
ViewModel:-
public class MyImageViewModel
: Xamarin.Forms.View
{
public static readonly BindableProperty MyImageAsBytesProperty = BindableProperty.Create<MyImageViewModel, byte[]>(p => p.MyImageAsBytes, default(byte[]));
public byte[] MyImageAsBytes
{
get { return (byte[])GetValue(MyImageAsBytesProperty); }
set { SetValue(MyImageAsBytesProperty, value); }
}
}
转换器:-
public class MyByteToImageSourceConverter
: IValueConverter
{
public object Convert(object pobjValue, Type pobjTargetType, object pobjParameter, System.Globalization.CultureInfo pobjCulture)
{
ImageSource objImageSource;
//
if (pobjValue != null)
{
byte[] bytImageData = (byte[])pobjValue;
//
objImageSource = ImageSource.FromStream(() => new MemoryStream(bytImageData));
}
else
{
objImageSource = null;
}
//
return objImageSource;
}
public object ConvertBack(object pobjValue, Type pobjTargetType, object pobjParameter, System.Globalization.CultureInfo pobjCulture)
{
throw new NotImplementedException();
}
}
【讨论】: