我创建了一个自定义控件ColorToggleButton,它继承了ToggleButton . 在相应的.xaml文件中,for 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)));
}
1 回答
在您的控件中,您是否提供了带有DefaultStyleKeyProperty覆盖的静态构造函数?