Using “await” in a converter (IValueConverter) not

2019-07-19 11:06发布

I have a converter in my Windows Phone application but it seems you cannot use "await" methods in it?

public object Convert(object value, Type targetType, object parameter, string language)
{
    _IDataService = ServiceLocator.Current.GetInstance<IDataService>();

    string imageUrlId = (string)value;

    byte[] imageByte = await iDataService.GetImage(imageUrlId);

    return LoadImageAsync(imageByte);
}

If I make the method async Task it says IValueConverter has no method Task async. This converter returns type ImageSource.

3条回答
迷人小祖宗
2楼-- · 2019-07-19 11:38

You can't change the signature of the Convert method since you have to provide an implementation for all the methods of the IValueConverter interface.

What I usually do is loading in the images of the view-model asynchronously from the backend, not on the UI thread. With the proper bindings, the images will be displayed on your UI as soon as it is loaded.

查看更多
forever°为你锁心
3楼-- · 2019-07-19 11:39

I have an older answer here that mostly addresses this problem (but see below - one of the helper types is somewhat dated).

The core of the problem is that asynchronous work is actually improper for a value converter to do. What you're really doing is telling WPF "to cast this type to this other type, first call a web service..."

So, IMO any asynchronous behavior is better done in other parts of the system (ViewModel, service layer, etc). Asynchronous work can be easily represented in a ViewModel by using my NotifyTask type.

However, my older answer does have a working "asynchronous value converter". Note that the TaskCompletionNotifier type in that answer has a newer implementation.

查看更多
可以哭但决不认输i
4楼-- · 2019-07-19 11:44

You could use .result () after async function call

Like, byte[] imageByte = iDataService.GetImage(imageUrlId).result ();

查看更多
登录 后发表回答