Search code examples
c#xamarin.formsbindable

Xamarin.Forms SetBinding to Image so that it refreshes when its Source changes


I am trying to have images in my page update / re-draw when I change their ImageSource - this will help me have them re-load async.

I thought having a bindable property for the imageSource bound to the image was a start, but it is not updating the image. I have tried a large number of ways including a viewModel approach with an OnPropertyChanged event, but I don't think I quite understood this.

This binding also has to be done in code, this is just how the app is written (minimal xaml).

So far my general approach has been:

Bindable property

public static readonly BindableProperty ImageFileProperty = BindableProperty.Create("ImageProperty", typeof(string), typeof(CustomImageClass));

public string ImageProperty { get { return (string)GetValue(ImageFileProperty); } set { SetValue(ImageFileProperty, value); } }

Inside the CustomImageClass constructor:

this.SetBinding(ImageFileProperty, "ImageProperty");

From here I would like to to have the image change when I update the ImageSource and have the image change. I hope this is specific enough, I think all the different examples bound to the xaml have confused me in how I need to do it in code.


Solution

  • Sorry the poor english

    I guess there's a lot of problem here...

    If I understand well, you wanna create a BindableProperty in your CustomImageClass. Is that right? If yes, so you can use the default convention to the bindable property name's, like this (note that I changed the type too):

    public static readonly BindableProperty ImageFileProperty =
            BindableProperty.Create("ImageFile", typeof(ImageSource), 
            typeof(CustomImageClass));
    
    public ImageSource ImageFile
    {
        get{ return (string)GetValue(ImageFileProperty); }
        set{ SetValue(ImageFileProperty, value); }
    }
    

    You can't to set bind to this property you've just create in your constructor. This will be used when you're consuming the class (in xaml or c#).

    Now you have to use your property to set the image where you wanna show. I think you should have a variable or private property in this class that is of Image type, for example 'image', so, inside the constructor you should do

    image = new Image();
    image.BindingContext = this;
    image.SetBinding(Image.Source, nameof(ImageFile));
    

    Let me know if I missunderstood, please. I hope that helps you.