2012-04-06 90 views
1

iv'e在视图模型得到了一个MVVM应用,WPF NotSupportedException异常

public CommandViewModel()   
    { 
     Messenger.Default.Register<CustomerSavedMessage>(this, message => 
     { 
      Customers.Add(message.UpdatedCustomer); 
     }); 
    } 

    private ObservableCollection<Customer> _customers; 
    public ObservableCollection<Customer> Customers 
    { 
     get { return _customers; } 
     set 
     { 
      _customers = value; 
      OnPropertyChanged("Customers"); 
     } 
    } 

客户势必在我看来,一个组合框。

在不同的视图模型

我提出在不同的线程 一个CustomerSavedMessage当我尝试处理NotSupportedException异常被抛出以下消息在注册的处理程序委托上述 消息:

{"This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread."} 

我显然需要为交叉线程操作使用Dispatcher对象, ,但我无法弄清楚这是如何从视图模型完成的。

还我认为,该框架将知道如何通过结合处理之间的交叉线程..

我怎样才能在发送器线程的Customers.Add(message.UpdatedCustomer)上执行?

回答

2

您可以使用Application.Current.Dispatcher来获取Dispatcher应用程序的主线程或捕获调度程序在您的ViewModel构造函数(Dispatcher.CurrentDispatcher)中。

例如:

Messenger.Default.Register<CustomerSavedMessage>(this, message => 
{ 
    Application.Current.Dispatcher.Invoke(
     new Action(() => Customers.Add(message.UpdatedCustomer))); 
});