C# – Setting a style on Control type not working

cnetstyleswpfxaml

I'm writing a very basic WPF dialog and want to apply a simple style to all objects that inherit from the Control class. The code I'm using:

<Window.Resources>
    <Style TargetType="{x:Type Control}">
        <Setter Property="Margin" Value="20"/>
    </Style>
</Window.Resources>
 <StackPanel>
    <TextBlock Text="some text"/>
    <TextBox x:Name="x_NameTextBox"/>
    <StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
        <Button x:Name="x_CancelButton" Click="x_CancelButton_Click" Content="Cancel"/>
        <Button x:Name="x_OkButton" Click="x_OkButton_Click" Content="OK"/>
    </StackPanel>
</StackPanel>
</Window>

The Style defined above doesn't change the layout of the window at all unless I specify a key and set the style on each individual object, which is exactly what I'm trying to avoid. It also works for more specific types (setting the TargetType to Button, for example.)

Any ideas why this isn't working?

Best Answer

Every control when it gets instantiated it gets its Style from the explicitly defined resource or look for the immediate parent where it can get a default style. In your case the Button control will get its default Style from the platform because your App haven't defined one. Now that platform Button Style has no way to know about your custom defined Control base style. Because styles will look for a base style only when you explicitly define BasedOn

So you got only two ways 1. Define Style for every control - which you don't want I think. 2. Define Styles for the controls you are interested and set the BasedOn

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

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