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

StackOverflow https://stackoverflow.com/questions/1303634

我声明了一个要应用于项目中所有按钮的样式,该样式位于 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" />

问题是,如果您分配一个键,它不是全局的,您必须在每个窗口/范围上调用它。

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

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

但我正在寻找比愚蠢地重新声明所有样式更好的东西。

有帮助吗?

解决方案

尝试这个:

<Style TargetType="{x:Type StackPanel}" BasedOn="{StaticResource {x:Type StackPanel}}">
  <!-- ... -->
</Style>

我已经在 App.xaml 的 ResourceDictionary 中声明了我的基本样式,如果我在像这样的特定窗口中覆盖它们,它通常会起作用。

其他提示

在全局资源字典中的某个位置,您可以使用键定义基本样式。此基本样式针对的类型是您打算应用该样式的所有类型的基础。然后,您可以定义针对所需类型并基于上述基本样式的样式。

<Style
    x:Key="upDownBaseStyle"
    TargetType="{x:Type Control}">
    <Setter
      Property="Margin"
      Value="2" />
    <Setter
      Property="HorizontalAlignment"
      Value="Stretch" />
    <Setter
      Property="VerticalAlignment"
      Value="Center" />
  </Style>

  <Style
    TargetType="{x:Type xceed:IntegerUpDown}"
    BasedOn="{StaticResource upDownBaseStyle}">
  </Style>

  <Style
    TargetType="{x:Type xceed:DoubleUpDown}"
    BasedOn="{StaticResource upDownBaseStyle}">
  </Style>

现在,最后两种样式将应用于应用程序中的所有 IntegerUpDown 和 DoubleUpDown 控件,而无需提及任何键。

所以基本规则:基本样式必须有引用它的键,而派生样式可能没有,因此它们可以在没有任何键的情况下应用 - 仅通过目标类型。

我建议您可能在这里寻找的是通常通过创建用户控件来实现的主样式或行为场景。如果您要创建一个应用了“全局”样式的新按钮控件,那么在任何要使用该控件的地方,您都可以简单地添加任何“新的 样式或在需要时覆盖样式。

如果您还没有创建用户控件,它们很容易实现。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top