"The calling thread cannot access this object because a different thread owns it." While using Dispa
- by Sdry
I have an application, that I want to load additional xaml files, being resourcedictionaries controling the style of the application.
Yet when trying to add a loaded ResourceDictionary to the mergeddictionaries I get an InvalidOperationException saying "The calling thread cannot access this object because a different thread owns it." at a point where I am not even using multiple threads.
The application contains a usercontrol which loads the xaml file through a background worker, adding the loaded ResourceDictionaries to an Observablecollection.
When I pass on a selected theme(=ResourceDictionary) to a function in the mainwindow of the application, it goes wrong.
public void LoadTheme(Theme theme)
{//sdry 2010-4-22
if(theme !=null){
this._dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =>
{
MessageBox.Show("SKIN TEST: " + theme.Name); //> oke
#if (SHOWDEBUGINFO)
_selectedTheme = theme.Name; //>oke
#endif
Application.Current.Resources.MergedDictionaries.Clear(); //>oke
Application.Current.Resources.MergedDictionaries.Add(theme.ResourceDictionary); //> InvalidOperationException
//the theme object has a property named ResourceDictionary of type ResourceDictionary containing the loaded xaml
}));
}
}
My first reaction was to use the Disatcher.Invoke, even not knowing how I would not be on the gui thread, which doesn't solve a thing.
So maybe my loaded theme belongs to a different thread ? but its originating from a property of a usercontrol, which should be the same thread. And its accesable untill trying to use the ResourceDictionary.
This makes me confused, and not very aware of how to proceed, any help is appreciated.