WPF UserControl cannot find XAML resource in referencing project

resourceswpfxaml

In my WPF project i keep a user control in a separate library project. The user control accesses resources in a separate XAML file, like this:

<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/Resources/ViewResources.xaml" />
        </ResourceDictionary.MergedDictionaries>
        <!-- Local styles here -->
    </ResourceDictionary>
</UserControl.Resources>

The resource file, ViewResources.xaml, resides in a folder in the control library project named Resources. It has the default build action (Page) and custom tool (MSBuild:Compile).

The problem is when I reference the control library in my WPF application and use the user control. At runtime, I get the following XamlParseException:

Set property 'System.Windows.ResourceDictionary.Source' threw an exception.

…which wraps the IOException:

Cannot locate resource 'resources/viewresources.xaml'.

How can I fix this? I have tried to change the resource file's build action to "content" and have it copied to the output directory (that works for files and similar "dumb" resources). But to no avail. Also, it doesn't work property in the user control then.

Is there a better way to specify the path?

Will I have to move the resource file to the application project (I'd rather not, as it belongs in the user control's domain).

Best Answer

Found it.

Turns out there is a better way to specify the path, Pack URIs. I changed the XAML to the following:

<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="pack://application:,,,/RoutingManager;component/Resources/ViewResources.xaml" />
        </ResourceDictionary.MergedDictionaries>
        <!-- Local styles here -->
    </ResourceDictionary>
</UserControl.Resources>

and that fixed it.