图片来源基于 Xamarin.Forms 中的属性值

Image source based on properties value in Xamarin.Forms

我有一个继承自 FFImageLoading.Forms.CachedImage 的自定义 MyCachedImage,它在 ListView 中用于显示图像。 此图像的来源由 2 个属性组成:作为实体的自定义对象和作为大小的整数。 假设实体是 "city" 对象且大小为 10,则图像源将为“http://..../city/10/image.png

仅当两个属性都被赋值时才必须设置图片来源。

所以,我的答案是,如何以及何时创建源 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>

我想知道什么时候创建那个字符串,我找到了正确的解决方案。 设置所有属性时调用 OnBindingContextChanged,因此:

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