确保OnPropertyChanged()被调用的MVVM WPF应用程序UI线程 [英] Making sure OnPropertyChanged() is called on UI thread in MVVM WPF app

查看:705
本文介绍了确保OnPropertyChanged()被调用的MVVM WPF应用程序UI线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个WPF应用程序使用MVVM模式是我写的,我有一个做这件事一个后台进程,但需要得到它的状态更新了到用户界面。

In a WPF app that I'm writing using the MVVM pattern, I have a background process that doing it's thing, but need to get status updates from it out to the UI.

我使用MVVM模式,所以我的视图模型知道几乎没有任何的视图(UI)的是presenting模型给用户。

I'm using the MVVM pattern, so my ViewModel knows virtually nothing of the view (UI) that is presenting the model to the user.

说我有我的视图模型下面的方法:

Say I have the following method in my ViewModel:

public void backgroundWorker_ReportProgress(object sender, ReportProgressArgs e)
{
    this.Messages.Add(e.Message);
    OnPropertyChanged("Messages");
}

在我看来,我有一个列表框绑定到消息财产(一名单,其中,串> )的视图模型的。 OnPropertyChanged 通过调用 PropertyChangedEventHandler INotifyPropertyChanged的接口的作用>。

In my view, I have a ListBox bound to the Messages property (a List<string>) of the ViewModel. OnPropertyChanged fulfills the role of the INotifyPropertyChanged interface by calling a PropertyChangedEventHandler.

我需要确保 OnPropertyChanged 被称为UI线程 - 我该怎么办呢?我已经尝试了以下内容:

I need to ensure that OnPropertyChanged is called on the UI thread - how do I do this? I've tried the following:

public Dispatcher Dispatcher { get; set; }
public MyViewModel()
{ 
    this.Dispatcher = Dispatcher.CurrentDispatcher;
}

然后添加以下到 OnPropertyChanged 方法:

if (this.Dispatcher != Dispatcher.CurrentDispatcher)
{
    this.Dispatcher.Invoke(DispatcherPriority.Normal, new ThreadStart(delegate
    {
        OnPropertyChanged(propertyName);
    }));
    return;
}

但没有奏效。任何想法?

but this did not work. Any ideas?

推荐答案

WPF自动老帅属性更改到UI线程。但是,它并没有元帅收集的变化,所以我怀疑你的加入邮件会导致失败。

WPF automatically marshals property changes to the UI thread. However, it does not marshal collection changes, so I suspect your adding a message is causing the failure.

您可以在名帅手动添加自己(见下例),或使用类似的这个技术我的博客上讲述了一段时间了。

You can marshal the add manually yourself (see example below), or use something like this technique I blogged about a while back.

手动编组:

public void backgroundWorker_ReportProgress(object sender, ReportProgressArgs e)
{
    Dispatcher.Invoke(new Action<string>(AddMessage), e.Message);
    OnPropertyChanged("Messages");
}

private void AddMessage(string message)
{
    Dispatcher.VerifyAccess();
    Messages.Add(message);
}

这篇关于确保OnPropertyChanged()被调用的MVVM WPF应用程序UI线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆