Async implementation of IValueConverter

前端 未结 3 1081
一整个雨季
一整个雨季 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:13

    Below Code is perfect working to me.

    Example.xaml

    
          
             
          
          
       
    
    

    ExampleConverterWithAsync.cs

    public class ExampleConverterWithAsync : IValueConverter
    {
        public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
                return new TaskNotifier(Task.run(async() => 
           {
                Task.Delay(1_000);  // replace your job
                return "Hello World";
           }));
        }
    
        public override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => Binding.DoNothing;
    
        public class TaskNotifier : ViewModelBase
            where T : class
        {
            private T _asyncValue;
            public T AsyncValue
            {
                get => _asyncValue;
                set { this.SetValue(ref _asyncValue, value); }
            }
            public TaskNotifier(Task valueFunc)
            {
                Task.Run(async () =>
                {
                    AsyncValue = await valueFunc;
                });
            }
        }
    }
    

提交回复
热议问题