相关疑难解决方法(0)

确保在MVVM WPF应用程序的UI线程上调用OnPropertyChanged()

在我正在使用MVVM模式编写的WPF应用程序中,我有一个后台进程可以做到这一点,但需要从UI获取状态更新.

我正在使用MVVM模式,因此我的ViewModel几乎不知道向用户呈现模型的视图(UI).

假设我的ViewModel中有以下方法:

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

在我看来,我有一个ListBox绑定到List<string>ViewModel 的Messages属性(a ). 通过调用a OnPropertyChanged来完成INotifyPropertyChanged接口的角色PropertyChangedEventHandler.

我需要确保OnPropertyChanged在UI线程上调用 - 我该怎么做?我尝试过以下方法:

public Dispatcher Dispatcher { get; set; }
public MyViewModel()
{ 
    this.Dispatcher = Dispatcher.CurrentDispatcher;
}
Run Code Online (Sandbox Code Playgroud)

然后将以下内容添加到OnPropertyChanged方法中:

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

但这没用.有任何想法吗?

.net wpf multithreading mvvm

35
推荐指数
2
解决办法
3万
查看次数

标签 统计

.net ×1

multithreading ×1

mvvm ×1

wpf ×1