Update listview asynchronously

2.2k views Asked by At

So far I'm having trouble finding any similar question, so I'll ask here:

I have an item source (say, a list of 10 person) bound to a ListView. The list is populated asynchronously, and let's say, the list item would be added one item (person) at a second. Could you teach me how to make my ListView displays the item right from the first item instead of waiting for the tenth item then displays them all together?

Any working sample would be appreciated.

Thank you in advance.

XAML:

    <ListView ItemsSource="{Binding tempData, Mode=TwoWay}" Width="1000" Height="1000">
        <ListView.ItemTemplate>
            <DataTemplate>
                <Grid Width="100" Height="50">
                    <TextBlock Text="{Binding name}"/>
                </Grid>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

CS (frankly I'm using cloud service, so the actual code is basically like:

await app.WorkWith().Data<Person>().GetAll().ExecuteAsync();

So, I take it that the line above would mean:

        private async Task<List<Person>> GenerateItem()
    {
        List<Person> tempData = new List<Person>(); 

        tempData.Add(new Person() { name = "name1"});
        await Task.Delay(1000);
        tempData.Add(new Person() { name = "name1" });
        await Task.Delay(1000);
        tempData.Add(new Person() { name = "name1" });
        await Task.Delay(1000);
        tempData.Add(new Person() { name = "name1" });
        await Task.Delay(1000);
        tempData.Add(new Person() { name = "name1" });
        await Task.Delay(1000);
        tempData.Add(new Person() { name = "name1" });
        await Task.Delay(1000);
        tempData.Add(new Person() { name = "name1" });
        await Task.Delay(1000);
        tempData.Add(new Person() { name = "name1" });
        await Task.Delay(1000);
        tempData.Add(new Person() { name = "name1" });
        await Task.Delay(1000);
        return tempData;
    }

And finally:

        private async void Populate()
    {

        List<Person> tempData = await GenerateItem();
        listView1.ItemsSource = tempData;            
    }
1

There are 1 answers

0
Matej Putnok On

Just use ObservableCollection .... When item is added to collection then CollectionChanged are raised and your listview/gridview updated itself