views:

1035

answers:

5

I have an Image control with it's source bound to a property on an object(string url to an image). After making a service call, i update the data object with a new URL. The exception is thrown after it leaves my code, after invoking the PropertyChanged event.

The data structure and the service logic are all done in a core dll that has no knowledge of the UI. How do I sync up with the UI thread when i cant access a Dispatcher?

PS: Accessing Application.Current.RootVisual in order to get at a Dispatcher is not a solution because the root visual is on a different thread(causing the exact exception i need to prevent).

PPS: This only is a problem with the image control, binding to any other ui element, the cross thread issue is handled for you.

+1  A: 

Have you tried implementing INotifyPropertyChanged?

Jonathan Parker
A: 

The property getter for RootVisual on the Application class has a thread check which causes that exception. I got around this by storing the root visual's dispatcher in my own property in my App.xaml.cs:

public static Dispatcher RootVisualDispatcher { get; set; }

private void Application_Startup(object sender, StartupEventArgs e)
{
    this.RootVisual = new Page();
    RootVisualDispatcher = RootVisual.Dispatcher;
}

If you then call BeginInvoke on App.RootVisualDispatcher rather than Application.Current.RootVisual.Dispatcher you shouldn't get this exception.

Rob Fonseca-Ensor
A: 

I ran into a similar issue to this, but this was in windows forms:

I have a class that has it's own thread, updating statistics about another process, there is a control in my UI that is databound to this object. I was running into cross-thread call issues, here is how I resolved it:

Form m_MainWindow; //Reference to the main window of my application
protected virtual void OnPropertyChanged(string propertyName)
{
  if(PropertyChanged != null)
    if(m_MainWindow.InvokeRequired)
      m_MainWindow.Invoke(
        PropertyChanged, this, new PropertyChangedEventArgs(propertyName);
    else
      PropertyChanged(this, new PropertyChangedEventArgs(propertyName);
}

This seems to work great, if anyone has suggestions, please let me know.

Brandon
+3  A: 
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => {...});

Also look here.

Phil
A: 

See the url , you will find a way to slove this http://www.jaylee.org/post/2010/01/02/WinForms-DataBinding-and-Updates-from-multiple-Threads.aspx

wota