因此,我认为这很简单,但显然将依赖项属性设置为null会导致异常。
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)));
当使用上面的代码并且以Value
的value
调用null
设置程序时,出现以下异常
System.InvalidOperationException: 'Nullable object must have a value.'
这完全没有道理。如果它是Nullable object
,那么根据定义,我应该可以将其设置为null。
所以我的问题是,有没有一种方法可以将可设置为null的依赖项属性设置为null?
注册依赖项属性时,应将typeof(object)
替换为typeof(int?)
:
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(int?), typeof(MyClass), new PropertyMetadata(default(int?), new PropertyChangedCallback(OnValueChanged)));
将int?
属性设置为null
或default(int?)
应该可以。