gpt4 book ai didi

c# - 向自定义控件添加依赖属性导致样式出现奇怪的错误

转载 作者:太空宇宙 更新时间:2023-11-03 21:49:56 25 4
gpt4 key购买 nike

我正在尝试创建一个从 ListBoxItem 扩展的自定义控件,如下所示:

public class MainNavListBoxItem : ListBoxItem
{
public MainNavListBoxItem()
{
this.DefaultStyleKey = typeof(MainNavListBoxItem);
}
}

我有一个在 ResourceDictionary 中定义的样式,如下所示:

<Style TargetType="assets:MainNavListBoxItem">
<Setter Property="Padding" Value="3"/>
<Setter Property="HorizontalContentAlignment" Value="Left"/>
<Setter Property="VerticalContentAlignment" Value="Top"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="TabNavigation" Value="Local"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="assets:MainNavListBoxItem">
<Grid Height="50">
<VisualStateManager.VisualStateGroups>
...

现在它可以像这样正常编译和运行,但是只要我向 MainNavListBoxItem 类添加一个额外的依赖属性,我就会开始出现这样的错误:

Failed to create a 'System.Windows.DependencyProperty' from the text 'Padding'.

如果我在样式中重新排列 Setter 标签,它将始终报告最上面的标签。

还有我的依赖属性代码供引用:

public ImageSource ImageDark
{
get { return (ImageSource)GetValue(ImageDarkProperty); }
set { SetValue(ImageDarkProperty, value); }
}
public static readonly DependencyProperty ImageDarkProperty =
DependencyProperty.Register("ImageDark", typeof(ImageSource), typeof(MainNavListBoxItem), new PropertyMetadata(0));

这是怎么回事?!我希望能够在样式中使用此 ImageDark 依赖属性!

我已经对这个错误进行了大量搜索,但似乎没有任何内容与这个问题相关。

最佳答案

这个问题是因为我忘记将依赖属性中的 new PropertyMetadata(0) 更改为 new PropertyMetadata(null)。谢谢肯特。

关于c# - 向自定义控件添加依赖属性导致样式出现奇怪的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15055332/

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