如何覆盖全局样式(没有x:Key),或者将命名样式应用于所有以类型为目标的控件?

Shi*_*mmy 43 wpf xaml styles resourcedictionary

我声明了一个我想要应用于项目中所有按钮的样式,样式位于ResourceDictionary中:

<Style TargetType="StackPanel">
    <Setter Property="Orientation" Value="Horizontal" />
    <Setter Property="VerticalAlignment" Value="Center"/>
    <Setter Property="HorizontalAlignment" Value="Center"/>
</Style>
Run Code Online (Sandbox Code Playgroud)

现在,在某些窗口中,我想继承此样式但添加一个值:

<Style TargetType="StackPanel"> 
    <Setter Property="Margin" Value="5"/>
</Style>
Run Code Online (Sandbox Code Playgroud)

问题是它不会继承全局样式,为了继承我必须为全局样式分配一个键:

<Style TargetType="StackPanel" x:Key="StackPanelStyle" />
Run Code Online (Sandbox Code Playgroud)

然后在窗口的XAML继承(或/和覆盖 - 可选)它:

<Style TargetType="StackPanel" BasedOn="StackPanelStyle" />
Run Code Online (Sandbox Code Playgroud)

问题是如果你分配一个密钥,它不是全局的,你必须在每个窗口/范围上调用它.

我的问题的解决方案应该是两个中的一个(还有什么我错过了吗?):

  1. 拥有带键的全局样式,可自动应用于整个应用程序中的所有目标控件.
  2. 一种在没有并且覆盖它的情况下引用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}"/
Run Code Online (Sandbox Code Playgroud)

但我正在寻找更好的东西,而不是愚蠢地重新宣布所有的风格.

Bot*_*000 66

试试这个:

<Style TargetType="{x:Type StackPanel}" BasedOn="{StaticResource {x:Type StackPanel}}">
  <!-- ... -->
</Style>
Run Code Online (Sandbox Code Playgroud)

我在App.xaml的ResourceDictionary中声明了我的基本样式,如果我在这样的特定窗口中覆盖它们,它通常可以工作.

  • 在Silverlight中如何做到这一点? (2认同)