tags:

views:

449

answers:

2

Hi, I was just poking around a bit in WPF and wanted all elements on my Window to share the same margin. I found that all Controls that are capable of having a margin derive from FrameworkElement so I tried the following:

<Window.Resources>
<Style TargetType="{x:Type FrameworkElement}">
    <Setter Property="Margin" Value="10" />
</Style>
</Window.Resources>

And, this doesn't work. I can apply this to all Buttons, but not to all Elements that derive from Button. Am I missing something or is this simply not possible?

Am I the only one feeling like using CSS for WPF would have been a good idea?

+5  A: 

Unfortunately, you cannot apply styles to the base FrameworkElement type; while WPF will let you write the style, it will not apply it to the controls that derive from it. It appears that this also applies to subtypes of FrameworkElement, e.g. ButtonBase, the supertype of Button/ToggleButton/RepeatButton.

You can still use inheritance, but you will have to use the explicit 'BasedOn' syntax to apply it to the control types you want it to apply to.

Nicholas Armstrong
Thanks. I thought about that too, but it feels terribly slow if I'd like one style to be applied to ALL elements that are on a Window.
Tigraine
+1  A: 

The issue is that when searching for a style WPF does not search through all classes from which the current one derives. However you can give the style a key and apply it to all elements for which you wish to have a common property. If a property is specified in the style that cannot be applied to the element you are styling, it is ignored.

Aran Mulholland