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?