views:

517

answers:

1

I have a WPF UserControl, which I use in a WinForms Control within an ElementHostControl. Then I start a WPF Window, while the Windows Form is still open. If I then close the WPF Window, and try to add a Child Element to my WPF UserControl, it crashes at "InitializeComponent()" (of the Child Element) with the exception:

"A first chance exception of type 'System.Configuration.ConfigurationErrorsException' occurred in System.Configuration.dll. Additional information: This element is not currently associated with any context"

I found out why it happens, but I don't know how to solve the problem. If I leave out this code:

public static void EnsureApplicationResources()
    {
        if (Application.Current == null)
        {
            // create the Application object
            new Application();
            string assemblyName = System.IO.Path.GetFileNameWithoutExtension(
                Assembly.GetExecutingAssembly().ManifestModule.Name);

            // merge in your application resources
            Application.Current.Resources.MergedDictionaries.Add(
                Application.LoadComponent(new Uri("/KolonistenClient;component/KolonistenResourceDictionary.xaml", UriKind.RelativeOrAbsolute))
                as ResourceDictionary);
        }
    }

then everything is fine. I need that though, because of the fact that my ResourceDictionary (and thus also my defined styles and templates) is otherwise not available throughout the WPF Window and Controls. This I found out about here

Is there any way to combine the best of both worlds? Keeping my ResourceDictionary, while preventing the application from crashing?

A: 

I solved it eventually by adding the ResourceDictionary in each Window manually through xaml. This way the UserControl in my WinForms stays unaffected.

Still don't understand exactly why it crashed though, unfortunately.

<Window.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/KolonistenClient;component/KolonistenResourceDictionary.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Window.Resources>
Avalon