I am developing a Wpf application which retrieves the data from a database using EF.
I have some ListView controls which are filled with some tables of the database so in order to prevent from blocking the UI while retrieving the data I do as follows:
Task tsk = Task.Factory.StartNew(() =>
{
ItemsSource = Database.SomeTable();
});
The ItemsSource variable is an ObservableCollection which is bound to the ItemsSource property of a ListView.
The thing is that, as expected, while loading the data the UI keeps responsive. My problem is that the ListView is empty until all the data is loaded. So I would like to see element by element appearing in the ListView. Is there a way to do that?? I have tried which a foreach loop with no luck.
Thanks in advance.
Perhaps using
Task.Delay
to allow the UI to render the changes before adding the next item in the foreach will workExample:
This can be accomplished by dispatching the addition of new elements to your observable collection using the Disptacher's BeginInvoke method, called from your task. Something like:
//MainWindow.xaml
//MainWindow.xaml.cs
If you have a large amount of records you may want to chunk it, otherwise just call the Disptacher for each record.