locked
LISTVIEW NOT getting refresh to show data when UPDATNG WHEN OBSERVABLECOLLECTION IS CHANGE using worker thread to main thread RRS feed

  • Question

  • I Have a listview the binds to an observeablecollection. I have a user which calls tell the main thread to empty the observable collection and repopulate it. The listview shows the original data disappearing when the observable colllection is cleared but does not show the data when the obeserveable collection is repopulated. If I debug the codeand step through it line by line then when I am done stepping through the code the listview will display the data. Is there a way to force the listview to refresh its view
    Saturday, August 15, 2009 4:46 PM

Answers

  • When operating on an ObservableCollection it needs to be done from the UI thread.

    This is because changes to the collection fire a CollectionChanged event which will ultimately call methods on UI elements. In Wpf, all UI elements have to be interacted with from the UI thread.

    One solution to repopulate the OC is to create all the data objects in a List<T> on the worker thread, then post them on the UI thread:

             List<MyData> list = new List<MyData>();
    
             /* ... create/add data */
    
             // post data
             App.Current.MainWindow.Dispatcher.Invoke(
                DispatcherPriority.Normal,
                (ThreadStart)delegate
                {
                   collection.Clear();
    
                   foreach (var item in list)
                   {
                      collection.Add(item);
                   }
    
                });
    
    cz
    • Marked as answer by Linda Liu Wednesday, August 19, 2009 7:27 AM
    Saturday, August 15, 2009 9:03 PM

All replies

  • When operating on an ObservableCollection it needs to be done from the UI thread.

    This is because changes to the collection fire a CollectionChanged event which will ultimately call methods on UI elements. In Wpf, all UI elements have to be interacted with from the UI thread.

    One solution to repopulate the OC is to create all the data objects in a List<T> on the worker thread, then post them on the UI thread:

             List<MyData> list = new List<MyData>();
    
             /* ... create/add data */
    
             // post data
             App.Current.MainWindow.Dispatcher.Invoke(
                DispatcherPriority.Normal,
                (ThreadStart)delegate
                {
                   collection.Clear();
    
                   foreach (var item in list)
                   {
                      collection.Add(item);
                   }
    
                });
    
    cz
    • Marked as answer by Linda Liu Wednesday, August 19, 2009 7:27 AM
    Saturday, August 15, 2009 9:03 PM
  • You might also try to Override INotificationChange in the obervablecollection

    lstMyListView.Items.Rerfresh();

    Kenneth
    Sunday, August 16, 2009 2:02 AM