This question is probably a duplicate, but I couldn't find it on SO.
If I have a container Window
, StackPanel
, Grid
, etc. is there any way I can apply a Style
to all the controls of a certain type, that are contained within it?
I can apply property changes, by using Container.Resources
and setting individual changes to a TargetType
, but when I tried setting the Style
of the target, I get an error, telling me I can't set Style
.
Is there any way to do this in XAML?
Sort of, depending on what you are trying to set. If the properties are properties of a common base class then yes, you can. You also have more options in WPF than Silverlight because you can inherit styles. For example...
<Window.Resources>
<Style x:Key="CommonStyle" TargetType="FrameworkElement">
<Setter Property="Margin" Value="2" />
</Style>
<Style TargetType="StackPanel" BasedOn="{StaticResource CommonStyle}">
</Style>
<Style TargetType="Grid" BasedOn="{StaticResource CommonStyle}">
</Style>
<Style TargetType="Button" BasedOn="{StaticResource CommonStyle}">
<Setter Property="Background" Value="LimeGreen" />
</Style>
</Window.Resources>
The common style, CommonStyle
would be inherited by the 3 implicit styles. But you can only specify properties that are common to all FrameworkElement classes. You couldn't set Background in CommonStyle because FrameworkElement does not provide a Background property. So even though Grid and StackPanel have Background (inherited from Panel) it is not the same Background property that Button has (inherited from Control.)
Hope this helps get you on your way.