Can I add resources or ResourceDictionary to the style?

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 it 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 crashes with an error about the value of the Setter property cannot be zero (although it is clearly not equal to zero).

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 is a way to combine ResourceDictionary into a style.

+6
styles wpf xaml resourcedictionary
source share
2 answers

StackPanel.Resources not a DependencyProperty , and therefore I do not believe that you can set this property in style.

+4
source share

Try adding a style for each TargetType to the DockPanel Style.Resources style.

I did something similar with DockPanel Style. All buttons or separators are required to be added to the DockPanel to get the style consistent.

Here is an example:

 <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> 
+3
source share

All Articles