gpt4 book ai didi

c# - 样式 : BasedOn and DefaultStyleKeyProperty. OverrideMetadata

转载 作者:行者123 更新时间:2023-11-30 22:12:43 30 4
gpt4 key购买 nike

当我在 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。

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

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

最佳答案

来自 MSDN页:

A control typically overrides the default value of this property to be its own type, but in some cases could also use a base type for which a style in the theme dictionaries exists. This is only practical if the control templates of the base control entirely define the visual representation of that derived control, and if whatever additional members the derived types expose do not require additional elements as part of the control template.

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

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

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

关于c# - 样式 : BasedOn and DefaultStyleKeyProperty. OverrideMetadata,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19568199/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com