Setting the property of the TargetType property to the base class

I just made a little joke in WPF and wanted all the elements in my window to share the same margin. I found that all controls that may have a margin get from FrameworkElement, so I tried the following:

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

And it does not work. I can apply this to all buttons, but not to all elements that are produced from Button. Am I missing something or is it just not possible?

I feel that the only thing I like to use CSS for WPF was a good idea?

+38
styles wpf targettype
Jun 22 '09 at 11:26
source share
2 answers

Unfortunately, you cannot apply styles to the base type FrameworkElement; while WPF allows you to write a style, it will not apply to the controls that flow from it. Apparently, this also applies to FrameworkElement subtypes, for example. ButtonBase, supertype Button / ToggleButton / RepeatButton.

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

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

+53
Jun 22 '09 at 13:28
source share

The problem is that when searching for a style, WPF does not search for all classes from which the current is inferred. However, you can give the style a key and apply it to all the elements for which you want to have a common property. If a property is specified in a style that cannot be applied to the style you set, it is ignored.

+7
Sep 24 '09 at 3:44
source share



All Articles