How do you set a Nullable Dependency Property to Null?

Viewed 689

So I thought this would be straight forward enough but apparently setting a dependency property to null causes an exception.

    public int? Value
    {
        get => (int?)GetValue(ValueProperty);
        set {SetValue(ValueProperty, value); }
    }

    public static readonly DependencyProperty ValueProperty =
        DependencyProperty.Register("Value", typeof(object), typeof(MyClass), new PropertyMetadata(default(int?), new PropertyChangedCallback(OnValueChanged)));

When the above code is used and the Value setter is called with a value of null I get the following exception

System.InvalidOperationException: 'Nullable object must have a value.'

Which makes entirely no sense. If it's a Nullable object then by definition, I should be able to set it to null.

So my question is, is there a way to have a dependency property with a nullable type while also being able to set it to null?

1 Answers

You should replace typeof(object) with typeof(int?) when you register the dependency property:

public static readonly DependencyProperty ValueProperty = 
    DependencyProperty.Register("Value", typeof(int?), typeof(MyClass), new PropertyMetadata(default(int?), new PropertyChangedCallback(OnValueChanged)));

Setting an int? property to null or default(int?) should work.

Related