tags:

views:

14

answers:

1

Hello,

I have created a View Model in Silverlight. This View Model has an event defined as:

public event EventHandler Data_Loaded;

I want to "Raise" this event when data from a service call has been completed. This will allow my UI to respond properly. Please note, it is not just a simple binding scenario, that is why I want the event.

The service call is made via a HttpWebRequest. Once this request is done, I'm properly parsing the results. I'm trying to let the UI know that I'm done, but initially I was getting an error that said "Invalid cross-thread access". I spoke to a co-worker who told me I should use the SynchronizationContext.Current to raise an event. Unfortunately, I do not understand how to do this. Can someone please explain it to me?

A: 

You need to use the Dispatcher to force the event to be raised on the UI thread.

Deployment.Current.Dispatcher.BeginInvoke(() => DataLoaded(this,EventArgs.Empty));
Stephan
I'm not raising an event on the UI. The UI is subscribing to an event on the ViewModel. If I use the Dispatcher, it seems like the UI is too tightly coupled to the ViewModel. Am I wrong?
The key to the problem is if your UI is listening to this event, the event has to be thrown from the UI thread. While it's possible to do with the SyncronizationContext, it can be a real pain because SyncronizationContext.Current will be null if you are not on the UI thread. This means you need to get the SyncronizationContext while on the UI thread and store that somewhere. Then you can use that to marshall the call back to the correct thread. In general in Silverlight I wouldn't consider it tightly coupled as long as you use Deployment and not App.RootVisual to access the Dispatcher.
Stephan