Async implementation of IValueConverter

前端 未结 3 1070
一整个雨季
一整个雨季 2020-11-27 15:25

I have an asynchronous method which I want to trigger inside an IValueConverter.

Is there a better way than forcing it to be synchronous by calling the

3条回答
  •  粉色の甜心
    2020-11-27 16:12

    The alternative approach is to make your own control which supports async sources or data.

    Here is the example with the image

        public class AsyncSourceCachedImage : CachedImage
    {
        public static BindableProperty AsyncSourceProperty = BindableProperty.Create(nameof(AsyncSource), typeof(Task), typeof(AsyncSourceSvgCachedImage), null, propertyChanged: SourceAsyncPropertyChanged);
    
        public Task AsyncSource
        {
            get { return (Task)GetValue(AsyncSourceProperty); }
            set { SetValue(AsyncSourceProperty, value); }
        }
    
        private static async void SourceAsyncPropertyChanged(BindableObject bindable, object oldColor, object newColor)
        {
            var view = bindable as AsyncSourceCachedImage;
            var taskForImageSource = newColor as Task;
    
            if (taskForImageSource != null)
            {
                var awaitedImageSource = await taskForImageSource;
    
                view.Source = awaitedImageSource;
            }
        }
    }
    

    Moreover, you might implement the loading activity indicator over the image until the task will be resolved.

提交回复
热议问题