问题
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.
回答1:
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.
回答2:
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.
回答3:
You could use .result () after async function call
Like, byte[] imageByte = iDataService.GetImage(imageUrlId).result ();
来源:https://stackoverflow.com/questions/34240426/using-await-in-a-converter-ivalueconverter-not-working