DependencyProperty.UnsetValue 屬性
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
指定屬性系統所使用的靜態值,而不是 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
屬性值
未設定值的 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 值。 如需詳細資訊,請參閱深入了解資料繫結。