Xamarin Forms, using async to apply ListView ItemS

2019-05-23 10:19发布

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.

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;
    }
}

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;
    });
}

2条回答
Melony?
2楼-- · 2019-05-23 10:25

you can try with this way:

      Task.Run(()=> {
            downloadAllInformation();
             Device.BeginInvokeOnMainThread( ()=> {
                myListView.ItemSource = ... 
             });

         });

in this way you manage asynchronously the filling of listView.

I've tried this with a lot of data and the performances are better.

查看更多
手持菜刀,她持情操
3楼-- · 2019-05-23 10:39

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.

查看更多
登录 后发表回答