简体   繁体   中英

Unset DependencyProperty throws NullReferenceException

I am working on a Windows Store App. A custom class uses a DependencyProperty of an enum type. When I try to access this property without having set it before the app crashes with an NullReferenceException. The same code runs without any problem on 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:

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).

So what it is the problem here? Why does this code run on Windows Phone and not on Windows Store Apps?

You have set the default value to null at the end of your DependencyProperty declaration. Set it to ItemDisplayType.None . You may be able to use default(ItemDisplayType) , but I'm not sure if that will work.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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