語言

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

哨兵值用於未設定的值。

範例

此範例用 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 是一個哨兵值,用於依賴屬性系統無法確定所請求的依賴屬性值的情況。 使用UnsetValue而非 null,因為 null 是大多數參考型態值的有效屬性值,且是相依屬性中元資料中常用的 DefaultValue 。

UnsetValue 從 DependencyObject.GetValue 呼叫中回傳。 當你呼叫 DependencyObject.GetValue 作為相依屬性時,以下條件中有一個總是成立:

  • 相依屬性在元資料中設定了預設值,該值會被回傳。 這個值可能來自屬性的元資料 DefaultValue。 這可能是 null。
  • 其他價值透過價值優先順序被確立(例如套用風格或評估綁 定 ),預設值已不再適用。 即使被特別設定,這仍然可能是 null。 欲了解更多價值優先順序,請參閱 依賴性質概覽。

當請求的屬性尚未在本地設定時,DependencyObject.ReadLocalValue 會回傳UnsetValue。

Note

請勿註冊預設值為 UnsetValue的相依屬性。 這會讓房地產消費者感到困惑,並在房地產系統中產生意想不到的後果。

UnsetValue 應從提供資料綁定轉換為相依屬性的 IValueConverter 實作回傳,無論轉換器無法轉換來源值。 轉換器不應該在 IValueConvert.Convert 中拋出例外,這些例外會以執行時異常的形式出現,你需要在 UnhandledException 中新增處理,甚至更糟的是,使用者會看到它們是真正的執行時例外。 轉換器實作應遵循一般綁定模式,即任何失敗綁定都不做任何事,也不提供值, UnsetValue 而 null 綁定引擎理解的哨兵值。 如需詳細資訊,請參閱 深入數據綁定。

適用於

另請參閱