[英]Xamarin - Show image from base64 string
我對 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; }
}
項目查看.xaml:
<StackLayout VerticalOptions="FillAndExpand" Padding="5,20,5,0" >
<Label Text="Items" VerticalOptions="Center" Font="35" HorizontalOptions="Center" />
<ListView x:Name="list" ItemsSource="{Binding Items}">
<ListView.ItemTemplate>
<DataTemplate>
<ImageCell
Text="{Binding ItemName}"
Detail="{Binding Infos, StringFormat='{0}'}"
Image.Source="{Binding Path=Image}">
</ImageCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
我正確地顯示了我的標簽,但圖像沒有。 有人可以解釋我做錯了什么嗎?
Image
屬性的類型應該是ImageSource
,而不是Image
,因為您顯然想要綁定ImageCell的ImageSource
屬性。 除此之外,在屬性getter中調用OnPropertyChanged
永遠不會起作用,因為必須在綁定(或任何其他使用者)獲取更改的屬性值之前觸發PropertyChanged
事件。
而不是Image.Source="{Binding ...}
,而不是正確的綁定
<ImageCell ... ImageSource="{Binding Path=Image}" />
應該像這樣聲明屬性:
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
屬性值,你可以把只讀,並作出相應的OnPropertyChanged
在呼叫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;
}
}
您還可以在表單的字符串處構造
image.Source = $"data:image/png;base64, {base64Image}";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.