基于父样式的WPF样式
假设我有一个容器元素(如网格)的WPF样式,它自动将样式应用于其子项,如下所示:基于父样式的WPF样式,wpf,xaml,Wpf,Xaml,假设我有一个容器元素(如网格)的WPF样式,它自动将样式应用于其子项,如下所示: <Window.Resources> <Style TargetType="Grid" x:Key="FormStyle"> <Style.Resources> <Style TargetType="Label"> <Setter Property="FontSize" Value=
<Window.Resources>
<Style TargetType="Grid" x:Key="FormStyle">
<Style.Resources>
<Style TargetType="Label">
<Setter Property="FontSize" Value="50"/>
</Style>
</Style.Resources>
</Style>
</Window.Resources>
那么一切都好了
我当然可以只命名样式,但肯定有一种更简单/不太冗长的方式
谢谢以下是静态资源的查找过程:
BasedOn=“{StaticResource{x:Type Label}”
WPF首先查找Grid
内部定义的ResourceDictionary
,然后查找窗口
—网格的逻辑父级—及其资源,最后查找应用程序级资源。由于样式是FormStyle
中的嵌套样式,WPF在任何地方都找不到它,默认为基本样式
进一步了解上的静态资源查找行为
要获得所需的输出,您可以:
1) 将您的标签
样式移出表单样式
并移入窗口。Resources
2) 将FormStyle
中的标签样式合并到Grid
元素中定义的标签样式中
<Grid Style="{StaticResource FormStyle}">
<Grid.Resources>
<Style TargetType="Label">
<Setter Property="Foreground" Value="Red"/>
<Setter Property="FontSize" Value="50"/>
</Style>
</Grid.Resources>
<Label Content="Blah"/>
</Grid>
非常感谢,非常有帮助。移动到窗口/网格有点挫败了这一点,因为它是一种应用程序级风格,由多个窗口/控件使用(我没有提到这一点)。第三点很好
<Style TargetType="Label">
<Setter Property="FontSize" Value="50"/>
</Style>
<Grid Style="{StaticResource FormStyle}">
<Grid.Resources>
<Style TargetType="Label">
<Setter Property="Foreground" Value="Red"/>
<Setter Property="FontSize" Value="50"/>
</Style>
</Grid.Resources>
<Label Content="Blah"/>
</Grid>
<Window.Resources>
<Style TargetType="Grid" x:Key="FormStyle">
<Setter Property="Label.FontSize" Value="50"/>
</Style>
</Window.Resources>