我正在研究xamarin。单击加载时的选项卡式页面。我想在后台通过api加载数据并显示加载指示器。
protected override void OnAppearing()
{
base.OnAppearing();
if (!_appeared)
{
// Want this to be run behind
ProductViewData productViewData = new ProductViewData();
products = productViewData.GetProductList("10");
count = 10;
productListView.ItemsSource = products;
_appeared = true;
}
}
感谢您的帮助。
答案 0 :(得分:0)
您可以使方法异步并等待您的响应。您不应该从另一个线程更新UI线程,因此使用Task.Run是一个坏主意。 Take a look at Async Programming if you need more details
protected override async void OnAppearing()
{
base.OnAppearing();
if (!_appeared)
{
try
{
ProductViewData productViewData = new ProductViewData();
// make the method asynchronous
products = productViewData.GetProductListAsync("10");
count = 10;
productListView.ItemsSource = products;
_appeared = true;
}
catch(Exception exception)
{
// good idea to catch any network exceptions
}
}
}
答案 1 :(得分:-1)
只需将Task.Run放入其中即可使用
protected override void OnAppearing()
{
base.OnAppearing();
if (!_appeared) // Avoid repeat loding
{
activity.IsEnabled = true;
activity.IsRunning = true;
activity.IsVisible = true;
var task = Task.Run(() =>
{
ProductViewData productViewData = new ProductViewData();
products = productViewData.GetProductList("10");
count = 10;
productListView.ItemsSource = products;
});
_appeared = true;
}
}