0

我有使用经典 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?

谢谢

4

1 回答 1

0

如果您无权访问 Dispatcher,则只需将 BeginInvoke 方法的委托传递给您的类:

public class YourViewModel {
public YourViewModel(Action<Action> beginInvoke)
{
    this.BeginInvoke = beginInvoke;
}

protected Action<Action> BeginInvoke { get; private set; }

private void SomeMethod()
{
    this.BeginInvoke(() => DoSomething());
} }

然后实例化它(从可以访问调度程序的类):

var dispatcherDelegate = action => Dispatcher.BeginInvoke(action); 
var viewModel = new YourViewModel(dispatcherDelegate);
于 2015-02-05T21:29:56.017 回答