wpf - 为什么在 App.xaml 中设置 Grid.Margin 时 TextBox 会得到填充?

标签 wpf styles

一个简单的窗口:

<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/

相关文章:

wpf - Databound WPF CheckBox 在值集上吃异常

java - TabLayout改变tabText颜色

css - 有没有办法设置 repeat-x 重复多长时间(以像素或百分比为单位)?

wpf - "inherit"wpf 中的主题风格

c# - WPF INotifyPropertyChanged 两种方式绑定(bind)奇怪的 Action

c# - 访问窗口资源中的命名元素

c# - WPF 错误样式仅在选项卡控件的可见选项卡上正确呈现

wpf - 如何向 WhiSTlerBlue ListView 添加交替行样式

c# - 当 ListView 的 ItemsSource 改变时触发事件

wpf - 在 WPF 中使用 AddLogicalChild、AddVisualChild 添加 UIElement