【发布时间】:2018-06-21 03:11:38
【问题描述】:
这是我的问题:
我在属性过滤器上绑定了一个 WPF 文本框。它用作过滤器:每次 TextBox.Text 更改时,都会设置 Filter 属性。
<TextBox Text="{Binding Filter, UpdateSourceTrigger=PropertyChanged, Mode=OneWayToSource}" />
现在在 ViewModel 上有我的 Filter 属性:每次过滤器更改时,我都会更新我的值。
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}");
}
}
由于不允许使用异步属性,如果我的绑定需要调用异步方法,我该怎么做?
【问题讨论】:
-
Async property in c#的可能重复
-
重新排列你的代码,这样你就不需要从你的属性设置器中调用异步方法...
-
如果你在一个函数中做了很多事情,尤其是可能出错的事情,重新考虑你的设计,让它成为一个属性。让它成为一个函数。
标签: wpf binding async-await