29

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?

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
ocodo
  • 29,401
  • 18
  • 105
  • 117

1 Answers1

45

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.

Josh
  • 68,005
  • 14
  • 144
  • 156
  • 17
    If a style doesn't have an x:Key field - it will apply to *all* objects of that type. So *all* StackPanels, Grids & Buttons will have that margin. – DefenestrationDay Jul 17 '12 at 08:57