我声明了一个风格,我想将其应用于项目中的所有按钮,这个风格存储在ResourceDictionary中:
<Style TargetType="StackPanel">
<Setter Property="Orientation" Value="Horizontal" />
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="HorizontalAlignment" Value="Center"/>
</Style>
现在,在某个窗口中,我想继承这个样式但添加一个值:
<Style TargetType="StackPanel">
<Setter Property="Margin" Value="5"/>
</Style>
问题在于它并没有继承全局样式,为了进行继承,我必须给全局样式分配一个键:
问题在于它没有从全局样式中继承,为了继承,我需要给全局样式分配一个键:
<Style TargetType="StackPanel" x:Key="StackPanelStyle" />
然后在窗口的 XAML 中继承(或/和覆盖 - 可选)它:
<Style TargetType="StackPanel" BasedOn="StackPanelStyle" />
问题在于,如果你分配了一个键,它并不是全局的,你必须在每个窗口/范围上调用它。
解决方法应该是以下两者之一(我是否漏掉了其他东西?):
- 有一个带有键的全局样式,自动应用于整个应用程序中的所有目标控件。
- 一种引用ResourceDictionary级别未命名样式且不覆盖它的方法。
我考虑过在命名样式旁重新声明样式(在ResourceDictionary中),实际上这是起作用的:
<!--In the ResourceDictionary-->
<Style x:Key="StackPanelStyle" TargetType="StackPanel">
<Setter Property="Orientation" Value="Horizontal" />
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="HorizontalAlignment" Value="Center"/>
</Style>
<!--In the app.xaml-->
<Style TargetType="StackPanel" BasedOn="{StaticResource StackPanelStyle}"/>
<!--In the window/page scope-->
<Style TargetType="StackPanel" BasedOn="{StaticResource StackPanelStyle}"/
但我正在寻找比愚蠢地重新声明所有样式更好的东西。
<Style TargetType="{x:Type StackPanel}" BasedOn="{StaticResource {x:Type StackPanel}}" x:Key="MyStackPanel">
。有没有不设置x:Key的解决方案? - chrigax:Key="{x:Type StackPanel}"
吗?(至少如果你正在使用WPF,对于Silverlight我不确定) - Botz3000