Style: BasedOn and DefaultStyleKeyProperty.OverrideMetadata

本文关键字:DefaultStyleKeyProperty OverrideMetadata and BasedOn Style | 更新日期: 2023-09-27 18:36:40

当我在Visual Studio中创建自定义控件时,会自动添加静态构造函数:

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

风格

<Style TargetType="{x:Type c:MyListBoxItem}">
  <Style.Resources>
     <!--SelectedItem with focus-->
     <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Red" />
 </Style.Resources>
</Style>

然后给出一个空布局。如果没有静态构造函数中的代码,布局是正确的。只要您不将OverridesDefaultStyle设置为 true。

当我向 Style 添加BasedOn="{StaticResource {x:Type ListBoxItem}}"时,无论是否使用静态构造函数代码,布局都是正确的。 OverridesDefaultStyle已经没有效果了。

我希望自定义控件的样式默认为基类型的样式。在我看来,静态构造函数中的代码似乎可以省略。
但是为什么它是默认生成的呢?

Style: BasedOn and DefaultStyleKeyProperty.OverrideMetadata

从 MSDN 页面:

控件通常会重写此属性的默认值为其自己的类型,但在某些情况下,也可以使用主题字典中存在样式的基类型。仅当基控件的控件模板完全定义派生控件的可视表示形式,并且派生类型公开的任何其他成员不需要其他元素作为控件模板的一部分时,这才实用。

在您的情况下,您希望自定义控件默认使用基控件样式。若要实现此目的,必须从静态构造函数中删除该行,或者将其替换为以下行以指示要使用基控件样式。

DefaultStyleKeyProperty.OverrideMetadata(typeof(MyListBoxItem), new FrameworkPropertyMetadata(typeof(ListBoxItem)));

我想,从静态构造函数中删除该行会更好。