WPF替换和扩展样式

时间:2011-07-27 04:20:13

标签: wpf xaml styles

如何更改WPF对控件的默认样式的想法?为什么这首先发生?在下面的XAML中,我声明了一个Style for Button,然后进一步声明一个新的Style,它覆盖了一个名为“HugeBut”的setter。我希望HugeBut是隐含的基于我的新的未命名风格,但显然它不是;

<Window.Resources>
  <Style TargetType="{x:Type Button}">
    <Setter Property="Foreground" Value="Black"/>
    <Setter Property="Template">
      <Setter.Value>
        <ControlTemplate TargetType="{x:Type Button}">
          <Border Background="Red">
            <ContentPresenter/>
          </Border>
        </ControlTemplate>
      </Setter.Value>
    </Setter>
  </Style>

  <!-- badness -->
  <Style TargetType="{x:Type Button}" x:Key="HugeBut">
    <Setter Property="Foreground" Value="Yellow"/>
  </Style>

  <!-- works, but I do not want to explicitly set the based-on. -->
  <Style TargetType="{x:Type Button}" x:Key="HugeBut" BasedOn="{StaticResource {x:Type Button}}">
    <Setter Property="Foreground" Value="Yellow"/>
  </Style>
</Window.Resources>

<Button Content="Regular" />
<Button Content="huge!" Style="{StaticResource HugeBut}"/>

你会想到两个红色按钮,一个是黑色文本,一个是黄色,但是Style HugeBut继承了我在未命名样式中未指定的所有值,这些值来自Button的系统默认主题(在我的例子中是Aero)。

我该怎么做才能改变这种行为?

2 个答案:

答案 0 :(得分:3)

看来答案就在这里:

http://wpfthemereplacer.codeplex.com/

从网站说明:

  

此库允许用户提供自己的资源字典   替换WPF加载的默认主题词典。这样做   所以你不必用它来装饰自定义样式   当你自己的自定义主题是什么时,BasedOn =“{StaticResource {x:Type ...}}”   在您的应用程序中使用。如果您有自定义,它也会如此   只提供增强功能但不需要的控件   替换样式,您不需要定义新样式或   创建自定义控件时覆盖DefaultStyleKey。

这正是我正在寻找的。这将允许我使用样式,因为它们旨在用于广泛“重新主题化”的应用程序,而不是通过设置全局样式进行主题化(然后处理追踪缺少的代码的一些代码) ,或由于WPF错误和其他限制而无法处理它)

答案 1 :(得分:0)

  

有效,但我不想明确设置基于。

好吧,如果你不想,我不知道你的框架必须