Search code examples
propertiesxamarin.formsffimageloading

Image source based on properties value in Xamarin.Forms


I've got a custom MyCachedImage that inherits from FFImageLoading.Forms.CachedImage, which is used in a ListView to display images. The source of this image is composed by 2 properties: a custom object as entity and an integer as size. Let's say if entity is a "city" object and size is 10 then the image source will be "http://..../city/10/image.png"

Image source must be setted only when both properties are valorized.

So, my answer is, how and when create the source url?

MyCachedImage.vb

public class MyCachedImage : CachedImage
{
    public static readonly BindableProperty EntityProperty =
        BindableProperty.Create(nameof(Entity), typeof(MyObject), typeof(MyCachedImage));
    public MyObject Entity
    {
        get { return (MyObject)GetValue(EntityProperty); }
        set { SetValue(EntityProperty, value); }
    }

    public static readonly BindableProperty SizeProperty =
        BindableProperty.Create(nameof(Size), typeof(int), typeof(MyCachedImage), defaultValue: 0);
    public int Size
    {
        get { return (int)GetValue(SizeProperty); }
        set { SetValue(SizeProperty, value); }
    }

   public MyCachedImage()
    {
    ???  set source here?
   }
   protected override void OnBindingContextChanged()
    {
    ???  set source here?
    }
}

MyPage.xaml

<ListView ....>
....
<control:MyCachedImage Size="10"
                     Entity="{Binding MyObject}"
                     WidthRequest="40"
                     HeightRequest="40" />
....
</ListView>

Solution

  • I was wondering on when create that string and I found the right solution. The OnBindingContextChanged is called when all properties are setted, so:

    protected override void OnBindingContextChanged()
    {
        base.OnBindingContextChanged();
        if (_source == string.Empty)
        {
            Source = Helpers.ImageHelper.UriFromEntity(Entity, ImageSize);
        }
    }