Xamarin – 从base64字符串显示图像

我是Xamarin和XAML的新手,这是我迄今为止在Android和iPhone使用的便携式项目中所做的事情(仅使用Android):

Item.cs(从JSON加载)

[JsonProperty("image")] private string ImageBase64 { get; set; } [JsonIgnore] private Xamarin.Forms.Image _image = null; [JsonIgnore] public Xamarin.Forms.Image Image { get { if (_image == null) { _image = new Xamarin.Forms.Image() { Source = Xamarin.Forms.ImageSource.FromStream(() => new MemoryStream(Convert.FromBase64String(ImageBase64))), BackgroundColor = Color.White, WidthRequest = 64, HeightRequest = 64, }; OnPropertyChanged("Image"); } return _image; } private set { _image = value; } } 

ItemsView.xaml:

   

我正确地显示了我的标签,但图像没有显示。 谁能解释一下我做错了什么?

我从未使用过Xamarin,但是你的代码存在一些明显的问题。

Image属性的类型应该是ImageSource ,而不是Image ,因为您显然想要绑定ImageCell的ImageSource属性。 除此之外,在属性getter中调用OnPropertyChanged永远不会起作用,因为必须绑定(或任何其他使用者)获取更改的属性值之前触发PropertyChanged事件。

而不是Image.Source="{Binding ...} ,而不是正确的绑定

  

应该像这样声明属性:

 private string imageBase64; public string ImageBase64 { get { return imageBase64; } set { imageBase64 = value; OnPropertyChanged("ImageBase64"); Image = Xamarin.Forms.ImageSource.FromStream( () => new MemoryStream(Convert.FromBase64String(imageBase64))); } } private Xamarin.Forms.ImageSource image; public Xamarin.Forms.ImageSource Image { get { return image; } set { image = value; OnPropertyChanged("Image"); } } 

如果您确实需要延迟创建Image属性值,可以将其设置为只读,并在ImageBase64 setter中进行相应的ImageBase64调用:

 private string imageBase64 public string ImageBase64 { get { return imageBase64; } set { imageBase64 = value; OnPropertyChanged("ImageBase64"); OnPropertyChanged("Image"); } } private Xamarin.Forms.ImageSource image; public Xamarin.Forms.ImageSource Image { get { if (image == null) { image = Xamarin.Forms.ImageSource.FromStream( () => new MemoryStream(Convert.FromBase64String(ImageBase64))); } return image; } }