Search code examples
wpfwinformsxamlresourcedictionary

Define WPF Resource Dictionary in Winform App


I am testing being able to create a WPF control that can be used in an existing Winforms application. With this test, the goal is to have globally used WPF resource dictionary.

My first step of defining the style settings in the control works fine.

<UserControl.Resources>
    <Style TargetType="Label">
        <Setter Property="Foreground" Value="Black"/>
        <Setter Property="Background" Value="LightYellow"/>
        <Setter Property="FontSize" Value="30"/>
    </Style>
    <Style TargetType="Label" x:Key="myHW">
        <Setter Property="Foreground" Value="Green"/>
        <Setter Property="Background" Value="LightBlue"/>
        <Setter Property="FontSize" Value="30"/>
    </Style>
    <Style TargetType="Label" x:Key="StatusMessage">
        <Setter Property="Foreground" Value="Black"/>
        <Setter Property="Background" Value="LightPink"/>
    </Style>
</UserControl.Resources>

Second was to then extract the style information to a dictionary XAML file and then reference it via the resource dictionary. This step is not working.

<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/Dictionaries/ResourceTest.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</UserControl.Resources>

Assembly name: test2

Path inside project: /Dictionaries/ResourceTest.xaml

Error received in development is:

Exception: An error occurred while finding the resource dictionary "/Dictionaries/ResourceTest.xaml".

I have tried variations of the URI syntax as presented by Microsoft.

Does the build action type for the xaml relate to the issue?


Solution

  • Thanks Jeff R. for the response. That was one of the issues.

    I continued messing with this and finally resolved multiple issues. Since this was being created in a Winforms app in a sandbox, I created a WPF application and then added a resource dictionary. A comparison was done between the two resource dictionary xaml files to identify any differences.

    The resource dictionary xaml file needed the following settings updated:

    • Build Action = Page
    • Custom Tool = XamlIntelliSenseFileGenerator

    Additionally, the proper opening tag on the dictionary file was missing.

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

    Lastly, since manually entering the source path wasn't working, I tried using the Properties page Source drop down selection which then filled in the needed path syntax that then matched what Jeff R. recommended.

    In summary, there were three issues:

    1. Resource dictionary file property settings
    2. XAML opening tag missing
    3. URI reference syntax