Xamarin - Show image from base64 string

后端 未结 1 1932
花落未央
花落未央 2020-12-03 17:23

I\'m pretty new to Xamarin and XAML stuff and here is what I\'ve done so far in my portable project used by Android & iPhone (only using Android):

Item.cs (loade

相关标签:
1条回答
  • 2020-12-03 18:19

    The type of your Image property should be ImageSource, not Image, as you apparently want to bind an ImageCell's ImageSource property. Besides that, calling OnPropertyChanged in a property getter never works, because the PropertyChanged event has to be fired before a binding (or any other consumer) can get a changed property value.

    Instead of Image.Source="{Binding ...}, the correct binding would have to be

    <ImageCell ... ImageSource="{Binding Path=Image}" />
    

    The properties should be declared like this:

    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");
        }
    }
    

    If you really need lazy creation of the Image property value, you could make it read-only, and make the corresponding OnPropertyChanged call in the ImageBase64 setter:

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题