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;
    }
}
Public Shared Function ClearSetProperty(targetObject As DependencyObject, targetDP As DependencyProperty) As Boolean
    If targetObject Is Nothing Or targetDP Is Nothing Then
        Throw New ArgumentNullException()
    End If
    Dim localValue As Object = targetObject.ReadLocalValue(targetDP)
    If localValue = DependencyProperty.UnsetValue Then
        ClearSetProperty = False
    Else
        targetObject.ClearValue(targetDP)
        ClearSetProperty = True
    End If
End Function

備註

UnsetValue 是 sentinel 值,用於相依性屬性系統無法判斷要求的相依性屬性值的情況。 UnsetValue 是使用而非 Null,因為 null 是大多數參考型別值的有效屬性值,而且是相依性屬性中繼資料中常用的 DefaultValue

UnsetValue 永遠不會從 DependencyObject.GetValue 呼叫傳回。 當您針對相 依性屬性呼叫 DependencyObject.GetValue 時 ,下列其中一個條件一律為 true:

  • 相依性屬性具有在中繼資料中建立的預設值,而且會傳回該值。 此值可能來自屬性中繼資料的 DefaultValue。 這可能是 Null
  • 有些其他值是透過套用樣式 (值優先順序來建立,或已) 評估 Binding,且預設值不再相關。 即使特別設定,這仍然可能是 Null。 如需值優先順序的詳細資訊,請參閱 相依性屬性概觀

DependencyObject.ReadLocalValue 會在要求的屬性尚未在本機設定時傳回 UnsetValue。

注意

請勿使用 UnsetValue 的預設值來註冊相依性屬性。 這會對屬性取用者造成混淆,而且屬性系統內會有非預期的結果。

UnsetValue 應該從 IValueConverter 實作傳回,這個實作會在資料系結中提供相依性屬性的轉換,不論轉換子無法轉換來源值的情況。 轉換器不應該在 IValueConverter.Convert中擲回該案例的例外狀況,這些例外狀況會顯示為執行時間例外狀況,而您需要在 UnhandledException 中新增處理,或更糟,但使用者似乎顯示為實際的執行時間例外狀況。 轉換子實作應遵循一般系結模式,讓任何失敗的系結不執行任何動作且未提供值,而 UnsetValue 而非 null 是系結引擎瞭解的 sentinel 值。 如需詳細資訊,請參閱深入了解資料繫結

適用於

另請參閱