2012-04-06 88 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))); 
}); 
相關問題