iv’e got an mvvm application ,
in a viewmodel :
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");
}
}
Customers is bound to a combobox in my view .
in a different viewmodel i raise a CustomerSavedMessage on a different thread
when i attempt to handle the message in the Register’s handler delegate above
a notsupportedexception is thrown with the following message :
{"This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread."}
i obviously need to use the Dispatcher object for the cross thread operation,
but i can’t figure out how this is done from the viewmodel .
also i thought that the framework would know how to handle cross threading between over binding ..
how can i execute the Customers.Add(message.UpdatedCustomer) on the Dispatcher thread ?
You can use
Application.Current.Dispatcherto getDispatcherfor application’s main thread or capture dispatcher in your ViewModel constructor (Dispatcher.CurrentDispatcher).For example: