0

i have a ObservableCollection which is bound to a ListBox in my View. In my ViewModel is a Command. In this Command i would like to update all MyObjects.

Sample Code:

foreach(MyObject in List)
myobject.Prop = HelperClass.downloadData();

the downloaddata function takes some time...

when i run the command for some minutes nothing happens... and suddenly the View is updated.

Can someone help me?

Thanks

user547064
  • 217
  • 1
  • 4
  • 14
  • See http://stackoverflow.com/questions/4759459/how-to-update-observablecollection-from-inside-a-backgroundworker-using-mvvm/4760266#4760266 – Wonko the Sane Jan 22 '11 at 15:20

1 Answers1

0

when doing GUI applications the thread that takes care of drawing the view is the same that run the events so if you in an event block this thread the ui will freeze, try to use background worker:

BackgroundWoker bg = new BackGroundWorker();

bg.DoWork += (sender,args) =>
{

foreach(MyObject in List)
myobject.Prop = HelperClass.downloadData();
};
bg.RunWorkerAsync();

The BackgroundWorker does your work in a different thread releasing the UI Thread. If the this code doesn't change anything on the UI u can simple queue an work item into the thread pool.

DVD
  • 1,744
  • 3
  • 17
  • 34
  • This doesnt work... i get the error: Must create DependencySource on same Thread as the DependencyObject. – user547064 Dec 18 '10 at 16:48
  • You need to create the background worker within the UI thread so it copys the Thread Execution Context of the UI to make changes to it. – DVD Dec 18 '10 at 16:59
  • I created the worker in the main code behind file after i called window.show() :( – user547064 Dec 18 '10 at 17:30
  • Make sure you're not updating the ObservableCollection from within the background thread - you can't do that. If you want to update an ObservableCollection from outside the UI thread, use the Dispatcher (e.g. App.Current.Dispatcher.Invoke(() => { collection.Add(whatever); }); ) – gerrod Jan 25 '11 at 07:16