开发者

Why does TextBox get a padding when Grid.Margin is set in App.xaml?

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:

Why does TextBox get a padding when Grid.Margin is set in App.xaml?

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">
<Applic开发者_开发技巧ation.Resources>
    <Style TargetType="Grid">
        <Setter Property="Margin" Value="8"/>
    </Style>
</Application.Resources>
</Application>

Strangely, the TextBox now gets a padding:

Why does TextBox get a padding when Grid.Margin is set in App.xaml?

Why?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜