Search code examples
wpfresourcedictionaryxamlparseexception

Cannot instantiate UserControl from another assembly - Resource cannot be found


I have a solution with two WPF projects: Primary and Secondary.

In the Primary project, a Window named PrimaryView instantiates an UserControl called SecondaryControl, defined in Secondary project.

SecondaryControl uses SecondaryStyle, which is defined in SecondaryResourceDictionary (as you might have guessed already, defined in SecondaryProject).

The fact is: when I try to run the solution, I get a XamlParseError, and digging InnerExceptions I eventually find the culprit, the ResourceNotFound error.

So my questions are:

  • If SecondaryControl and its SecondaryStyle are defined in the same assembly, why can't I instantiate it it PrimaryAssembly?

  • Should I make SecondaryStyle available to PrimaryProject namespace somehow? Why?


Solution

  • I try to help you by explanation how it works in my projects. A separate assembly contains a common control and common resource dictionary like this:

    CommonResources.xaml

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

    SomeCommonControl.xaml

    <UserControl x:Class="YourAssembly.SomeCommonControl"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    
        <UserControl.Resources>
            <ResourceDictionary>
                <ResourceDictionary.MergedDictionaries>
                    <ResourceDictionary Source="pack://application:,,,/YourAssembly;component/CommonResources.xaml" />
                </ResourceDictionary.MergedDictionaries>
            </ResourceDictionary>
        </UserControl.Resources>
    
        <!-- Some specific content -->
    
    </UserControl>
    

    I can use this control and resources from another assemblies and WPF-projects like this:

    <Window x:Class="YourWPFProject.SomeWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:common="clr-namespace:YourAssembly">
    
        <Window.Resources>
            <ResourceDictionary>
                <ResourceDictionary.MergedDictionaries>
                    <ResourceDictionary Source="pack://application:,,,/YourAssembly;component/CommonResources.xaml" />
                </ResourceDictionary.MergedDictionaries>
            </ResourceDictionary>
        </Window.Resources>
    
        <common:SomeCommonControl />
    
    </Window>
    

    I hope this will help you.