【发布时间】:2019-03-02 10:27:26
【问题描述】:
我正在为 Android 和 iOS 在 Xamarin Forms 中实现一个应用程序,它与 WebAPI (.NET) 通信以从数据库中检索信息。 在某些时候,我有一个带有几个选择器的屏幕。假设在picker1中我们选择了一个国家;然后在picker2中我们选择一个城市。
当在picker1中选择一个国家时,它会引发一个SelectedIndexChanged事件(称为OnSelectedCountry),该事件调用WebAPI从该特定国家检索城市,然后通过picker2.ItemsSource将城市名称绑定到picker2。
这会导致性能马虎,并且看起来应用在执行 OnSelectedCountry 时卡住了,因为来自 picker1 的国家/地区列表直到 OnSelectedCountry 结束才关闭。 选择国家/地区后,如何立即关闭 picker1 中的列表项?或在其顶部显示“加载”图像。
我已经尝试过 this thread 的解决方案,但没有奏效。
代码片段(为简单起见省略了变量模型):
XAML
<Picker x:Name="picker1" Title="Select a country" ItemDisplayBinding="{Binding name}" SelectedIndexChanged="OnSelectedCountry" IsEnabled="False"/>
<Picker x:Name="picker2" Title="Select a city" IsEnabled="False" ItemDisplayBinding="{Binding name}"/>
CS
...
private ObservableCollection<City> _replyCities;
...
async void OnSelectedCountry(object sender, EventArgs e)
{
Country selectedCountry = (Country)picker1.SelectedItem;
string decodedJson = await RestService.GetDataAsync(selectedCountry.name);
Reply reply = Newtonsoft.Json.JsonConvert.DeserializeObject<Reply>(decodedJsonInput);
_replyCities = new ObservableCollection<City>(reply.Cities);
picker2.ItemsSource = _replyCities;
picker2.IsEnabled = true;
}
与 WebAPI 的连接在 RestService 类中执行,例如:
public static async Task<String> GetDataAsync(string queryInput)
{ ... }
【问题讨论】:
-
在单独的任务中运行
标签: .net visual-studio xamarin xamarin.forms eventhandler