Search code examples
c#wpfxamlresourcedictionary

Use ResourceDictionary with other Styles in WPF


I am trying to use a ResourceDictionary and a Style in my WPF program. When I only have ResourceDictionary in <Window.Resources> everything works fine but as soon as I add a <Style> the program displays "Resource not found" for the Dictionary and I get an error "The resource "PlusMinusExpander" could not be resolved."

<Window.Resources>
    <Style x:Key="CurrencyCellStyle" TargetType="{x:Type DataGridCell}">
        <Setter Property="Foreground" Value="#dddddd" />
        <Style.Triggers>
            <Trigger Property="IsSelected" Value="True">
                <Setter Property="Background" Value="Transparent"/>
                <Setter Property="BorderBrush" Value="Transparent"/>
            </Trigger>
        </Style.Triggers>
    </Style>

    <ResourceDictionary x:Key="hello" Source="Assets/PlusMinusExpanderStyles.xaml" />
</Window.Resources>


<Expander Header="Plus Minus Expander" Style="{StaticResource PlusMinusExpander}" HorizontalAlignment="Right" Width="292">
    <Grid Background="Transparent">
        <TextBlock>Item1</TextBlock>
     </Grid>
</Expander>

I want to be able to do Style="{StaticResource PlusMinusExpander}" even after adding the CurrencyCellStyle Style. I have seen similar questions online but none of their solutions have worked for me yet. Is there a way to use both the Style and the ResourceDictionary?


Solution

  • The type of Window.Resources property is ResourceDictionary, so cannot put two different types of XAML element as brothers. Instead, you should:

    • Put a separated ResourceDictionary into the Window.Resources property and write the Style inside the ResourceDictionary.
    • Remove the x:Key property from the ResourceDictionary.

    <FrameworkElement.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Assets/PlusMinusExpanderStyles.xaml" />
            </ResourceDictionary.MergedDictionaries>
            <Style x:Key="CurrencyCellStyle" TargetType="{x:Type DataGridCell}">
                <Setter Property="Foreground" Value="#dddddd" />
                <Style.Triggers>
                    <Trigger Property="IsSelected" Value="True">
                        <Setter Property="Background" Value="Transparent"/>
                        <Setter Property="BorderBrush" Value="Transparent"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </ResourceDictionary>
    </FrameworkElement.Resources>