我有使用经典 MVVM 模式实现的 WPF 应用程序,但是 View、Model 和 ViewModel 是我的解决方案中的三个不同项目。
我的ViewModel 中有众所周知的AsyncObservebleCollection实现
public class MyVM : ViewModelBase
{
private RelayCommand _runCommand;
private AsyncObservebleCollection _messages;
public AsyncObservebleCollection<Message> Messages
{
get
{
return _messages;
}
set
{
_messages = value; NotifyPropertyChanged();
}
}
public ICommand RunCommand
{
get
{
if (_runCommand == null)
{
_runCommand = new RelayCommand(executeParam =>
bq.QueueTask(this.ExecuteCommand),
canExecuteParam => true);
}
return _runCommand;
}
}
}
bq.QueueTask(this.ExecuteCommand) -> backgroundWorker 正在后台线程上执行命令,它更新了我的视图中的 Messages 属性。
现在,我收到线程冲突异常,因为 AsyncObservebleCollection 没有 UI 的 SynchronizationContext,而且我知道 ViewModel 不应该知道 View,我该如何解决我的问题?如何使用 UI 的 SynchronizationContext 异步运行 RelayCommand 并更新 UI?
谢谢