views:

250

answers:

1

Our offsite development team created a Model with an ObservableCollection property. Now, I'm in charge of creating the ViewModel, and I'm having trouble because the said Model runs inside a BackgroundWorker (another thread)- which means I can't update the View by hooking the CollectionChanged events. Here's the workaround that I did:

private Model model = new Model();
public ObservableCollection<Entry> Entries { get; set; }

public ctor()
{
    BackgroundWorker peon = new BackgroundWorker();
    peon.DoWork += work;
    peon.RunWorkerCompleted += updateViewCollection;
    peon.RunWorkerAsync();
}

private void work(object sender, DoWorkEventArgs e)
{
    model.DoSomething();
}

private void updateViewCollection(object sender, RunWorkerCompletedEventArgs e)
{
    // model.entries is an ObservableCollection<Entry>
    foreach (Entry en in this.model.entries) 
    {
        if (!this.Entries.Contains(en))
            this.Entries.Add(en);
    }
}

Is there a better way to hook the ObservableCollection of the Model to the ObservableCollection of the View through a Threaded ViewModel?

+1  A: 

I am assuming you are using either wpf or silverlight. You hook the events the same as you would on a single thread, but marshal them back onto the Dispatcher object (Invoke()). Assuming your observable collection is thread safe you should have no problem.

MaLio