Search code examples
c#wpfxamlresourcedictionary

Parsing nested xaml files with XamlReader.Load()


I'm doing a XamlReader.Load method on a resource dictionary, which has a couple of merged dictionaries.

FileStream s = new FileStream(@"/Resources/Xaml/MainXaml.xaml", FileMode.Open);
var obj = XamlReader.Load(s);

MainXaml then loads a few other xaml files:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="first.xaml"></ResourceDictionary>
        <ResourceDictionary Source="second.xaml"></ResourceDictionary>       
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

Whenever I try to do this, I have get an exception:

'Set property 'System.Windows.ResourceDictionary.Source' threw an exception.' Line number '4' and line position '29'. ---> System.IO.IOException: Assembly.GetEntryAssembly() returns null.

Set the Application.ResourceAssembly property or use the pack://application:,,,assemblyname;component/ syntax to specify the assembly to load the resource from.

Even when I try including the assembly name in the Source, the error persits

<ResourceDictionary Source="/MyApp;first.xaml"></ResourceDictionary>

Solution

  • Use Pack Uri's

    <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/Assembly_Name;component/first.xaml"/>
            </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
    

    Or

     FileStream s = new FileStream(@"pack://application:,,,/Assembly_Name;component/Xaml/MainXaml.xaml", FileMode.Open);