Question

Is it possible to define a ResourceDictionary in a Style?

For example, suppose I wanted to have two different Styles for StackPanels and in one I want all the buttons to be blue and the other I want them to be red. Is this possible?

Something like

<Style x:Key="RedButtonsPanel" TargetType="{x:Type StackPanel}">
    <Setter Property="Orientation" Value="Horizontal" />
    <Setter Property="StackPanel.Resources">
        <Setter.Value>
            <ResourceDictionary>
                <Style TargetType="{x:Type Button}">
                    <Setter Property="Background" Value="Red" />
                </Style>
            </ResourceDictionary>
        </Setter.Value>
    </Setter>
</Style>

The above code fails with an error about the Property value of a Setter cannot be null (even though it's obviously not null).

I can do something like

<ResourceDictionary x:Key="RedButtons">
    <Style TargetType="{x:Type Button}">
        <Setter Property="Width" Value="100" />
        <Setter Property="Background" Value="Red" />
    </Style>
</ResourceDictionary>

<StackPanel Resources={StaticResource RedButtons} />

However I was wondering if there was a way to merge the ResourceDictionary into the style.

Was it helpful?

Solution

StackPanel.Resources is not a DependencyProperty and therefore I don't believe you will be able to set that property within the style.

OTHER TIPS

Try adding the Style(s) for each TargetType to the DockPanel Style.Resources.

I did something similar with a DockPanel Style. Wanted all Buttons or Separators added to the DockPanel to get styled in a consistent manner.

Here's a sample:

<Style x:Key="DockPanelToolBarStyle" TargetType="{x:Type DockPanel}">
   <Style.Resources>
     <Style TargetType="Button" BasedOn="{StaticResource ButtonToolBarStyle}" />
     <Style TargetType="Separator" BasedOn="{StaticResource SeparatorToolBarStyle}" />
   </Style.Resources>
   <Setter Property="Height" Value="45"/>
   <Setter Property="Background" Value="{StaticResource ToolBarBrush}"/>
</Style>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top