Xamarin表单,使用异步应用ListView ItemSource [英] Xamarin Forms, using async to apply ListView ItemSource

查看:83
本文介绍了Xamarin表单,使用异步应用ListView ItemSource的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前正在使用Xamarin Forms,并且正在使用从github

I am currently using Xamarin Forms and I am using the post method which I got from github RESTAPI. My application crashes whenever I try to apply the data to my ListView ItemsSource.

以下是当前执行的成功回调,它检索JSON并将其序列化并将其存储在名为listData的列表中.

The following is the success callback that is currently executed, and it retrieves the JSON and serialize it and storing it in a list called listData.

public class Home : ContentPage
{
    private ListView myListView;
    private List<Person> listInfo = new List<Person> { };

    RESTAPI rest = new RESTAPI();
    Uri address = new Uri("http://localhost:6222/testBackEnd.aspx");

    public Home ()
    {
        Dictionary<String, String> data = new Dictionary<String, String>();
        rest.post(address, data, success, null);

        Content = new StackLayout { 
            Children = 
            {
                myListView
            }
        };
    }

    public void success(Stream stream)
    {
        DataContractJsonSerializer sr = new DataContractJsonSerializer(typeof(List<Person>));
        listData = (List<Person>)sr.ReadObject(stream);
        //myListView.ItemsSource = listData;
    }
}

是因为它不是异步的,如果可以的话,如何使该方法异步?我以前在Windows Phone 8.1上使用以下等待代码进行过操作,是否有等效的Xamarin Forms可用?

Is it because it is not asynchronous, and if so how can I make this method asynchronous? I did one previously on Windows Phone 8.1 using the following await code, is there a Xamarin Forms equivalent available for it?

async public void success(Stream stream)
{
    DataContractJsonSerializer sr = new DataContractJsonSerializer(typeof(List<Person>));
    listData = (List<Person>)sr.ReadObject(stream);
    await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
    {
        myListView.ItemsSource = listData;
    });
}

推荐答案

如果是因为它是异步的,则应该(总是)在主线程中进行UI更改. 为此:

If it is because it is asynchronous, then you should do the UI change (always) in the main thread. To do so:

using Xamarin.Forms;
...
    Device.BeginInvokeOnMainThread(()=>{
        // do the UI change
    }

如果这不能解决问题,那么异步不是(唯一?)问题.

If this doesn't solve it, then async is not the (only?) problem.

这篇关于Xamarin表单,使用异步应用ListView ItemSource的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆