如何将可为空的依赖属性设置为Null?

问题描述 投票:2回答:1

因此,我认为这很简单,但显然将依赖项属性设置为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)));

当使用上面的代码并且以Valuevalue调用null设置程序时,出现以下异常

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

这完全没有道理。如果它是Nullable object,那么根据定义,我应该可以将其设置为null。

所以我的问题是,有没有一种方法可以将可设置为null的依赖项属性设置为null?

c# dependency-properties nullable
1个回答
1
投票

注册依赖项属性时,应将typeof(object)替换为typeof(int?)

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

int?属性设置为nulldefault(int?)应该可以。

© www.soinside.com 2019 - 2024. All rights reserved.