A simple window:
<Window x:Class="MyApp.MainWindow" xmlns="..." xmlns:x="...">
<Window.Resources>
<Style TargetType="Grid">
<Setter Property="Margin" Value="8"/>
</Style>
</Window.Resources>
<Grid>
<TextBox VerticalAlignment="Top" HorizontalAlignment="Left">Test</TextBox>
</Grid>
</Window>
It looks like this:
Now we remove Window.Resources
:
<Window x:Class="MyApp.MainWindow" xmlns="..." xmlns:x="...">
<Grid>
<TextBox VerticalAlignment="Top" HorizontalAlignment="Left">Test</TextBox>
</Grid>
</Window>
And add the style definition to App.xaml
:
<Application x:Class="MyApp.App" xmlns="..." xmlns:x="..." StartupUri="View\MainWindow.xaml">
<Application.Resources>
<Style TargetType="Grid">
<Setter Property="Margin" Value="8"/>
</Style>
</Application.Resources>
</Application>
Strangely, the TextBox now gets a padding:
Why?
XAML ValuesMargin="20,50" will be interpreted to mean a Thickness with Left and Right set to 20, and Top and Bottom set to 50. The default unit for a Thickness measure is device-independent unit (1/96th inch). You can also specify other units by appending the unit type strings cm , in , or pt to any measure.
The Padding property represents the distance between an element and its child elements, and is used to separate the control from its own content. Padding values can be specified on layout classes.
Padding represents the distance between the side of the control (which can be the margin) and its content. The content depends on the type of the control. Margin is outside the UI element, while Padding is inside it. Next Recommended Reading WPF: Textblock Vs Label.
Implicit Styles for elements that do not derive from Control (i.e. Grid) will be applied to all instances of that control when placed in the Application resources. But they will not be applied to certain instances when the Style is placed any where else.
Effectively, elements inside ControlTemplate are except from implicit Styles for their type, unless that Style is defined in application resources.
Since Grid is not a control (i.e. it doesn't derive from Control), placing it's Style in the application resources will affect every Grid in your application. This includes Grids defined in the ControlTemplate of controls, like TextBox.
More information can be found here.
I suppose the default content of textbox contains a grid while placing the inner content. When in application resources, the TextBox styling occurs, the Grid Style also gets applied to the Grid inside the TextBox.
But when the same Grid style is applied in window resources (i.e after global styling occurs), it does not affect the Grid inside the TextBox.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With