Skip to main content
 首页 » 编程设计

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

2024年02月20日12www_RR

我正在尝试创建一个从 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)。谢谢肯特。