语言

DependencyProperty.UnsetValue 属性

定义

指定由属性系统使用的静态值,而不是 null 指示属性存在,但不具有由属性系统或任何应用代码设置的值。

public:
 static property Platform::Object ^ UnsetValue { Platform::Object ^ get(); };
static IInspectable UnsetValue();
public static object UnsetValue { get; }
var object = DependencyProperty.unsetValue;
Public Shared ReadOnly Property UnsetValue As Object

属性值

Object

Platform::Object

IInspectable

未设置值的 sentinel 值。

示例

此示例使用 ReadLocalValue 检查现有本地值。 如果存在本地值(如未返回 UnsetValue指示),则通过调用 ClearValue 删除现有本地值。

public static bool ClearSetProperty(DependencyObject targetObject, DependencyProperty targetDP)
{
    if (targetObject == null || targetDP == null)
    {
        throw new ArgumentNullException();
    }
    object localValue = targetObject.ReadLocalValue(targetDP);
    if (localValue == DependencyProperty.UnsetValue)
    {
        return false;
    }
    else
    {
        targetObject.ClearValue(targetDP);
        return true;
    }
}

注解

UnsetValue 是一个 sentinel 值,用于依赖属性系统无法确定请求的依赖属性值的方案。 UnsetValue 的使用不是 null,是因为 null 它是大多数引用类型值的有效属性值,并且是依赖属性的元数据中经常使用的 DefaultValue 。

UnsetValue 从不从 DependencyObject.GetValue 调用中返回。 为依赖属性调用 DependencyObject.GetValue 时,以下条件之一始终为 true:

  • 依赖属性具有在元数据中建立的默认值,并返回该值。 此值可能来自属性元数据的 DefaultValue。 这可能是 null。
  • 其他一些值是通过值优先级建立的(例如应用了样式或评估 了绑定 ),并且默认值不再相关。 即使特别设置,这仍然可能是 null。 有关值优先级的详细信息,请参阅 依赖项属性概述。

当请求的属性尚未在本地设置时,DependencyObject.ReadLocalValue 将UnsetValue返回。

注释

不要将依赖属性注册为默认值 。UnsetValue 这将令属性使用者感到困惑,并且会在属性系统中产生意外后果。

UnsetValue 应从 IValueConverter 实现中返回,该实现在数据绑定中提供到依赖属性的转换,在这种情况下,转换器无法转换源值。 转换器不应在 IValueConverter.Convert 中为这种情况引发异常,这些异常将作为运行时异常显示,你需要在 UnhandledException 中添加处理,或者更糟,但用户似乎显示为实际的运行时异常。 转换器实现应遵循一般绑定模式,即任何失败的绑定不执行任何操作且不提供值, UnsetValue 而不是 null 绑定引擎理解的该情况的 sentinel 值。 有关详细信息,请参阅深入了解数据绑定。

适用于

另请参阅