如何覆盖全局样式(没有 x:Key),或者将命名样式应用于所有类型定位控件? [英] How to override a global style (that doesn't have an x:Key), or alternatively apply a named style to all type-targeted controls?
问题描述
我声明了一个我想应用于项目中所有按钮的样式,该样式位于 ResourceDictionary 中:
I declared a style that I want to apply to ALL the buttons in the project, the style resides in the ResourceDictionary:
<Style TargetType="StackPanel">
<Setter Property="Orientation" Value="Horizontal" />
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="HorizontalAlignment" Value="Center"/>
</Style>
现在,在某些窗口中,我想继承此样式但添加一个值:
Now, in some window, I want to inherit from this style but add a value:
<Style TargetType="StackPanel">
<Setter Property="Margin" Value="5"/>
</Style>
问题是它没有从全局样式继承,为了继承我必须为全局样式分配一个键:
The problem is that it doesn't inherit from the global style, in order to inherit I have to assign a key to the global style:
<Style TargetType="StackPanel" x:Key="StackPanelStyle" />
然后在窗口的 XAML 中继承(或/和覆盖 - 可选)它:
And then in the window's XAML inherit (or/and override - optional) it:
<Style TargetType="StackPanel" BasedOn="StackPanelStyle" />
问题是如果你分配一个键,它不是全局的,你必须在每个窗口/范围内调用它.
The problem is that if you assign a key, it's not global and you have to call it on each window/scope.
我的问题的解决方案应该是两者之一(还有什么我遗漏的吗?):
A solution to my question should be one of the two (is there anything else I am missing out?):
- 具有带键的全局样式,该样式会自动应用于整个应用程序中的所有目标控件.
- 一种引用 ResourceDictionary 级别未命名样式的方法,无需并覆盖它.
我想过在命名样式(在 ResourceDictionary 中)附近重新声明实际有效的样式:
I thought about redeclaring the styles near the named styles (in the ResourceDictionary) which actually works:
<!--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}"/
但我正在寻找比愚蠢地重新声明所有样式更好的东西.
But I am looking for better stuff than stupidly redeclare all the styles.
推荐答案
试试这个:
<Style TargetType="{x:Type StackPanel}" BasedOn="{StaticResource {x:Type StackPanel}}">
<!-- ... -->
</Style>
我已经在 App.xaml 的 ResourceDictionary 中声明了我的基本样式,如果我在这样的特定窗口中覆盖它们,它通常可以工作.
I have declared my base styles in a ResourceDictionary in App.xaml, if i override them in a specific window like this, it usually works.
这篇关于如何覆盖全局样式(没有 x:Key),或者将命名样式应用于所有类型定位控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!