Search code examples
wpfresourcedictionary

How to use Resource Dictionary by its Key?


I am trying to use my Resource Dictionary but it does not recognize the styles have created.

<Window.Resources>
    <RoutedUICommand x:Key="Add" Text="Add" />
    <RoutedUICommand x:Key="Cancel" Text="Cancel" />
    <RoutedUICommand x:Key="Exit" Text="Exit" />
    <ResourceDictionary x:Key="LightTheme" Source="/Themes/Light.xaml"/>
</Window.Resources>

When I delete x:Key from ResourceDictionary tag, it shows a message saying "Each dictionary must have an associated key"

But when I try to use one of my styles, it does not work.

<Button x:Name="AddNew" Style="{StaticResource RoundCorner}">

Solution

  • Merge the dictionary. To do that, you need to have an explicit ResourceDictionary element.

    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/Themes/Light.xaml"/>
            </ResourceDictionary.MergedDictionaries>
    
            <RoutedUICommand x:Key="Add" Text="Add" />
            <RoutedUICommand x:Key="Cancel" Text="Cancel" />
            <RoutedUICommand x:Key="Exit" Text="Exit" />
    
        </ResourceDictionary>
    </Window.Resources>