Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to target all controls (WPF Styles)

Can I specify a style that applies to all elements? I tried

<Style TargetType="Control">     <Setter Property="Margin" Value="0,5" /> </Style> 

But it did nothing

like image 780
Jiew Meng Avatar asked Nov 09 '10 06:11

Jiew Meng


People also ask

How can I find WPF controls by name or type?

FindName method of FrameworkElement class is used to find elements or controls by their Name properties. The FrameworkElement class is mother of all controls in WPF.

Where do you put styles in XAML?

The most common way to declare a style is as a resource in the Resources section in a XAML file. Because styles are resources, they obey the same scoping rules that apply to all resources. Put simply, where you declare a style affects where the style can be applied.

What is TextBlock WPF?

The TextBlock control provides flexible text support for UI scenarios that do not require more than one paragraph of text. It supports a number of properties that enable precise control of presentation, such as FontFamily, FontSize, FontWeight, TextEffects, and TextWrapping.


1 Answers

The Style you created is only targeting Control and not elements that derive from Control. When you don't set the x:Key it's implicitly set to the TargetType, so in your case x:Key="{x:Type Control}".

There isn't any direct way to specify a Style that targets all elements that derive from the TargetType of the Style. You have some other options.

If you have the following Style

<Style x:Key="ControlBaseStyle" TargetType="{x:Type Control}">     <Setter Property="Margin" Value="50" /> </Style> 

You can target all Buttons for example

<Style TargetType="{x:Type Button}" BasedOn="{StaticResource ControlBaseStyle}"/> 

or use the style directly on any element, e.g. Button

<Button Style="{StaticResource ControlBaseStyle}" ...> 
like image 78
Fredrik Hedblad Avatar answered Oct 01 '22 08:10

Fredrik Hedblad