开发者

ObservableCollection in Model + Threading in ViewModel

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?


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.


Take a look at this http://nuget.org/List/Packages/Caliburn.Micro.INPC

It has a view model base that implements property changed that automatically marshals to the ui thread. there is also a class that Extends ObservableCollection that does the same thing called BindableCollection.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜