Search code examples
c#xamarin.formsmvvm-lightffimageloading

How to hide/unload a CachedImage in xamarin forms


I am still kind of new to Xamarin forms and now I am using the Ffimagloading library to display a gif through my viewmodel's "DisplayImage" property. But after certain conditions are met, I want to hide/unload the image, so that it is no longer there. This is the CachedImage in my View:

                <ffimage:CachedImage Grid.Column="0"
                                   Source="{Binding DisplayImage}" />

And this is the corresponding part in my ViewModel:

    private ImageSource displayImage;

    public void DownloadAndAssignImage() {
        try
        {
            var response = await this.DownloadFile(new Uri("..."));
            if (response != null)
            {
                this.DisplayImage = ImageSource.FromStream(() => new MemoryStream(response));
                
            }
        }
        catch (Exception e)
        {
            Log.Error(e);
        }
    }


    public void HideImage()
    {
        // does not work
        this.DisplayImage = null;
        
        // does not work too
        this.DisplayImage = new byte[0];
    }

    public ImageSource DisplayImage
    {
        get => this.displayImage;
        set
        {
            this.displayImage= value;
            this.RaisePropertyChanged();
        }
    }

How can I make it, so that the CachedImage shows nothing again after having assigned an ImageSource to it through "DownloadAndAssignImage()"? Setting the ImageSource to null or to an empty byte[] array does not work. How exactly do I need to modify the "HideImage()" method?

Thanks for your help in advance!


Solution

  • use IsVisible

    <ffimage:CachedImage Grid.Column="0" IsVisible="{Binding ImageVisible}"
                                   Source="{Binding DisplayImage}" />
    

    then in your VM (you'll need to implement INotifyPropertyChanged)

    ImageVisible = false;