When writing a WPF application using MVVM I came across this exception when throwing events up to the UI. The problem was that the source events were being thrown from a SmartCard API on a separate thread and I needed to bubble an event up to the UI to update an ObservableCollection in the ViewModel of the current Window.
The problem was I need to cast the DataContext to the correct ViewModel and in order to do that I needed to be on the UI thread. To solve the problem you need to use the Dispatcher but in a very specific way in order to do the cast. Below is the code example I used:
// Need to use the dispatcher with the new SmartCard assemblies to check if needed
// There is a warehouse selection dropdown on the left menu. This Init() causes it to hook up to
// the SessionSecurity.UserAuthenticationChanged event to populate that dropdown.
if (!leftMenu.Dispatcher.CheckAccess())
{
// Use BeginInvoke with this delegate to pass method as parameter
// without declaring a custom delegate.
Dispatcher.BeginInvoke(new Action(() =>
{
((LeftMenuControlViewModel)leftMenu.DataContext).EvaluateUserState();
}), System.Windows.Threading.DispatcherPriority.Normal);
}
else
{
((LeftMenuControlViewModel)leftMenu.DataContext).EvaluateUserState();
}
0e12c9f9-8db0-49a2-8e64-9bc84219ee28|1|2.0
.Net Framework 4.0, C#
.Net Framework 4.0, C#