【发布时间】:2011-07-27 04:20:13
【问题描述】:
如何更改 WPF 对控件的 默认 样式的想法?为什么会发生这种情况?在下面的 XAML 中,我为 Button 声明了一个 Style,然后进一步声明了一个新的 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)继承了我未在未命名样式中指定的所有值。
我可以做些什么来改变这种行为?
【问题讨论】:
-
HugeBut(t)?!!我认为您必须指定 BasedOn。如果你不知道,它怎么会知道将这种风格建立在其他风格的基础上?
-
在扩展控件的默认样式时,我当然不需要需要指定 BasedOn。我想进入一种情况,其他一切都回落到的值完全由我选择,并且永远不会自动从默认样式中获取,除非我愿意。
-
实际上恰恰相反。除非您指定其他样式,否则它总是源自默认样式。