Bob*_*421 0 c# xamarin.ios async-await xamarin xamarin.forms
我正在使用 Visual Studio for Mac 编写一个非常基本的 Xamarin Forms 应用程序。此应用程序应与 Android 和 iOS 上的 PCL 配合使用。
我在 XAML 文件上有一个空的 TableView。我想要做的是用我将从网络服务中获取的数据填充这个 TableView。
这是我的 C# 代码:
HttpClient client = new HttpClient();
public async Task<List<MyItem>> LoadData()
{
try
{
var response = await client.GetAsync(new Uri("http://example.com/myservice.php"));
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<List<MyItem>>(content);
}
}
catch (Exception)
{
return null;
}
return null;
}
async void Handle_Clicked(object sender, System.EventArgs e)
{
activity_indicator.IsRunning = true;
var data = await LoadData();
activity_indicator.IsRunning = false;
mylistview.Root.Clear();
foreach (var item in data)
{
TableSection section = new TableSection() { Title = item.GroupTitle };
foreach (var subitem in item.subitems)
{
var cell = new TextCell() { Text = subitem.Title };
cell.Tapped += on_item_tapped;
section.Add(cell);
}
mylistview.Root.Add(section);
}
}
Run Code Online (Sandbox Code Playgroud)
我是等待和异步编程的新手。我曾经使用 iOS 委托开发原生 iOS 应用程序。我听说线程无法更新 UI:例如,我可以在 LoadData() 方法中进行一些 UI 更新吗?所以我想知道我的代码是否好。它看起来不错,因为它有效,但我想知道这样工作是否是一件好事?
归档时间: |
|
查看次数: |
2974 次 |
最近记录: |