简体   繁体   English

未设置DependencyProperty引发NullReferenceException

[英]Unset DependencyProperty throws NullReferenceException

I am working on a Windows Store App. 我正在使用Windows Store应用程序。 A custom class uses a DependencyProperty of an enum type. 自定义类使用枚举类型的DependencyProperty。 When I try to access this property without having set it before the app crashes with an NullReferenceException. 当我尝试在应用程序崩溃前使用NullReferenceException崩溃而未设置此属性时。 The same code runs without any problem on Windows Phone. 相同的代码在Windows Phone上运行没有任何问题。

public enum ItemDisplayType {
    None,
    Detail,
    Any,
}

public class CustomClass : UserControl {
    public CustomClass () {
        // No crash when DisplayType is set
        // DisplayType = ItemDisplayType.Any;
        this.InitializeComponent();
    }

    public static readonly DependencyProperty DisplayTypeProperty = DependencyProperty.Register("DisplayType", typeof(ItemDisplayType), typeof(CustomClass), null);
    public ItemDisplayType DisplayType{
        get { return (ItemDisplayType)GetValue(DisplayTypeProperty); }
        set {
            SetValue(DisplayTypeProperty, value);
        }
    }
}

I do not understand what's the problem here. 我不明白这里出了什么问题。 According to the documentation an unset DependencyProperty should return the default value: 根据文档,未设置的DependencyProperty应该返回默认值:

If a default value is not specified, the default value for a dependency property is null for a reference type, or the default of the type for a value type or language primitive (for example, 0 for an integer or an empty string for a string). 如果未指定默认值,则对于引用类型,依赖项属性的默认值为null;对于值类型或语言原语,该类型的默认值为null(例如,对于整数,为0;对于字符串,为空字符串) )。

So what it is the problem here? 那么这是什么问题呢? Why does this code run on Windows Phone and not on Windows Store Apps? 为什么此代码在Windows Phone而不是Windows Store Apps上运行?

You have set the default value to null at the end of your DependencyProperty declaration. 您已在DependencyProperty声明的末尾将默认值设置为null Set it to ItemDisplayType.None . 将其设置为ItemDisplayType.None You may be able to use default(ItemDisplayType) , but I'm not sure if that will work. 您可能可以使用default(ItemDisplayType) ,但不确定是否可以使用。

public static readonly DependencyProperty DisplayTypeProperty = DependencyProperty.Register("DisplayType", typeof(ItemDisplayType), typeof(CustomClass), ItemDisplayType.None);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM