一个简单的窗口:
<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>
它看起来像这样:
现在我们删除
Window.Resources
:<Window x:Class="MyApp.MainWindow" xmlns="..." xmlns:x="...">
<Grid>
<TextBox VerticalAlignment="Top" HorizontalAlignment="Left">Test</TextBox>
</Grid>
</Window>
并将样式定义添加到
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>
奇怪的是,TextBox 现在得到了一个填充:
为什么?
最佳答案
当放置在应用程序资源中时,非从控件(即网格)派生的元素的隐式样式将应用于该控件的所有实例。但是当样式放置在其他任何地方时,它们不会应用于某些实例。
实际上,ControlTemplate 中的元素不属于其类型的隐式样式,除非该样式是在应用程序资源中定义的。
由于 Grid 不是控件(即它不是从 Control 派生的),将它的 Style 放置在应用程序资源中将影响应用程序中的每个 Grid。这包括在控件的 ControlTemplate 中定义的网格,例如 TextBox。
更多信息可咨询here .
关于wpf - 为什么在 App.xaml 中设置 Grid.Margin 时 TextBox 会得到填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6944721/