Reputation: 6484
Here is my problem:
I have a WPF TextBox binded on the property Filter. It works as a filter: each time the TextBox.Text changes, the Filter property is set.
<TextBox Text="{Binding Filter, UpdateSourceTrigger=PropertyChanged, Mode=OneWayToSource}" />
Now on the ViewModel there is my Filter property: each time the filter changes I update my values.
private string _filter;
public string Filter
{
get { return _filter; }
set
{
_filter = value;
// call to an async WEB API to get values from the filter
var values = await GetValuesFromWebApi(_filter);
DisplayValues(values);
}
}
public async Task<string> GetValuesFromWebApi(string query)
{
var url = $"http://localhost:57157/api/v1/test/result/{query}";
// this code doesn't work because it is not async
// return await _httpClient.GetAsync(url).Result.Content.ReadAsStringAsync();
// better use it this way
var responseMessage = await _httpClient.GetAsync(url);
if (responseMessage.IsSuccessStatusCode)
{
return await responseMessage.Content.ReadAsStringAsync();
}
else
{
return await Task.FromResult($"{responseMessage.StatusCode}: {responseMessage.ReasonPhrase}");
}
}
As it is not allowed to use async property, what could I do to make my binding working if it needs to call an async method?
Upvotes: 5
Views: 10623
Reputation: 301
This works from a property setter & I use it:
set
{
System.Windows.Application.Current.Dispatcher.Invoke(async () =>{ await this.SomeMethodAsync(); });
}
with the async method for clarity:
Task SomeMethodAsync()
{
//fill in whatever fits your scenario
await Task.Run(()=> blah blah blah);
}
Upvotes: 1
Reputation: 3835
I will assume that DisplayValues method implementation is changing a property that is bound to the UI and for the demonstration I will assume it's a List<string>
:
private List<string> _values;
public List<string> Values
{
get
{
return _values;
}
private set
{
_values = value;
OnPropertyChange();
}
}
And it's bindings:
<ListBox ItemsSource="{Binding Values}"/>
Now as you said it is not allowed to make property setters async so we will have to make it sync, what we can do instead is to change Values property to some type that will hide the fact it's data comming from asynchronous method as an implementation detail and construct this type in a sync way.
NotifyTask
from Stephen Cleary's Mvvm.Async library will help us with that, what we will do is change Values property to:
private NotifyTask<List<string>> _notifyValuesTask;
public NotifyTask<List<string>> NotifyValuesTask
{
get
{
return _notifyValuesTask;
}
private set
{
_notifyValuesTask = value;
OnPropertyChange();
}
}
And change it's binding:
<!-- Busy indicator -->
<Label Content="Loading values" Visibility="{Binding notifyValuesTask.IsNotCompleted,
Converter={StaticResource BooleanToVisibilityConverter}}"/>
<!-- Values -->
<ListBox ItemsSource="{Binding NotifyValuesTask.Result}" Visibility="{Binding
NotifyValuesTask.IsSuccessfullyCompleted,
Converter={StaticResource BooleanToVisibilityConverter}}"/>
<!-- Exception details -->
<Label Content="{Binding NotifyValuesTask.ErrorMessage}"
Visibility="{Binding NotifyValuesTask.IsFaulted,
Converter={StaticResource BooleanToVisibilityConverter}}"/>
This way we created a property that represents a Task
alike type that is customized for databinding, including both busy indicator and errors propagation, more info about NotifyTask
usage in this MSDN articale (notice that NotifyTask
is consider there as NotifyTaskCompletion
).
Now the last part is to change Filter property setter to set notifyValuesTask to a new NotifyTask
every time the filter is changed, with the relevant async operation (no need to await
anything, all the monitoring is already embedded in NotifyTask
):
private string _filter;
public string Filter
{
get
{
return _filter;
}
set
{
_filter = value;
// Construct new NotifyTask object that will monitor the async task completion
NotifyValuesTask = NotifyTask.Create(GetValuesFromWebApi(_filter));
OnPropertyChange();
}
}
You should also notice that GetValuesFromWebApi method blocks and it will make your UI freeze, you shouldn't use Result
property after calling GetAsync
use await
twice instead:
public async Task<string> GetValuesFromWebApi(string query)
{
var url = $"http://localhost:57157/api/v1/test/result/{query}";
using(var response = await _httpClient.GetAsync(url))
{
return await response.Content.ReadAsStringAsync();
}
}
Upvotes: 7
Reputation: 149
You can do it like this. Beware that in "async void" you need to handle all exceptions. If you don't, the application can crash.
public class MyClass: INotifyPropertyChanged
{
private string _filter;
public string Filter
{
get { return _filter; }
set
{
RaisePropertyChanged("Filter");
_filter = value;
}
}
public MyClass()
{
this.PropertyChanged += MyClass_PropertyChanged;
}
private async void MyClass_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(Filter))
{
try
{
// call to an async WEB API to get values from the filter
var values = await GetValuesFromWebApi(Filter);
DisplayValues(values);
}
catch(Exception ex)
{
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
Upvotes: 4