【问题标题】:WPF Style HierarchyWPF 样式层次结构
【发布时间】:2012-11-21 05:22:50
【问题描述】:

我创建了一个自定义控件 ColorToggleButton,它继承了 ToggleButton。在相应的 .xaml 文件中,ColorToggleButton 的一个特定于 TargetType 和 BasedOn ToggleButton。

<Style TargetType="ctl:ColorToggleButton" BasedOn="{StaticResource {x:Type ToggleButton}}">

这很好用,但是如果我使用 x:Key 在窗口中应用另一种样式,如

<Style x:Key="SameContent"><Setter Property="Content" Value="Same Content" /></Style>
<ctl:ColorToggleButton Style={StaticResource SameContent} />

旧样式似乎完全被淘汰并被新样式所取代。我可以通过使用 BasedOn 来规避这个问题

<Style x:Key="SameContent" BasedOn="{StaticResource {x:Type ctl:ColorToggleButton}}"><Setter Property="Content" Value="Same Content" /></Style>
<ctl:ColorToggleButton Style={StaticResource MyKey} />

但这对我来说似乎违反直觉,因为如果我将样式应用于普通的 ToggleButton 或其他一些默认控件,我不会使用 BasedOn 属性。这是实施您自己的控制的标准方式吗?我做错了什么可怕的事情吗?

编辑:ColorToggleButton的静态构造函数如下:

static ColorToggleButton()
{
    DefaultStyleKeyProperty.OverrideMetadata(typeof(ColorToggleButton), new FrameworkPropertyMetadata(typeof(ColorToggleButton)));
}

【问题讨论】:

    标签: wpf xaml wpf-controls


    【解决方案1】:

    在您的控制下,您是否提供了带有 DefaultStyleKeyProperty 覆盖的静态构造函数?

    static ColorToggleButton()
    {
                DefaultStyleKeyProperty.OverrideMetadata(typeof(ColorToggleButton), new FrameworkPropertyMetadata(typeof(ColorToggleButton)));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-14
      • 1970-01-01
      相关资源
      最近更新 更多