How to target all controls (WPF Styles)

WpfUser InterfaceStyles

Wpf Problem Overview


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

Wpf Solutions


Solution 1 - Wpf

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}" ...>

Solution 2 - Wpf

As Fredrik Hedblad answered you can effect all elements that inherited from control.

But you can't apply style for textblock and button with the same style for example.

to do that:

    <Style x:Key="DefaultStyle" TargetType="{x:Type FrameworkElement}">
        <Setter Property="Control.Margin" Value="50"/>
    </Style>
    <Style TargetType="TextBlock" BasedOn="{StaticResource DefaultStyle}"/>
    <Style TargetType="Button" BasedOn="{StaticResource DefaultStyle}"/>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJiew MengView Question on Stackoverflow
Solution 1 - WpfFredrik HedbladView Answer on Stackoverflow
Solution 2 - Wpfqazwsx123View Answer on Stackoverflow