DependencyObject.CoerceValue(DependencyProperty) Method


強制轉型所指定相依性屬性的值。Coerces the value of the specified dependency property. 完成方式是叫用存在於呼叫 DependencyObject 之相依性屬性的屬性中繼資料中所指定的任何 CoerceValueCallback 函式。This is accomplished by invoking any CoerceValueCallback function specified in property metadata for the dependency property as it exists on the calling DependencyObject.

 void CoerceValue(System::Windows::DependencyProperty ^ dp);
public void CoerceValue (System.Windows.DependencyProperty dp);
member this.CoerceValue : System.Windows.DependencyProperty -> unit
Public Sub CoerceValue (dp As DependencyProperty)



要強制轉型之相依性屬性的識別項。The identifier for the dependency property to coerce.


指定的 dp 或其值無效或不存在。The specified dp or its value were invalid or do not exist.


下列範例會在 PropertyChangedCallback 執行中呼叫 CoerceValue,以做為相同類別上不同相依性屬性的 PropertyChangedCallbackThe following example calls CoerceValue within a PropertyChangedCallback implementation that is used as the PropertyChangedCallback for a different dependency properties on the same class. 這是在相依性屬性之間引進真正值相依性的常見模式。This is a common pattern for introducing true value dependencies between dependency properties.

private static void OnCurrentReadingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
Private Shared Sub OnCurrentReadingChanged(ByVal d As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs)
End Sub


除了透過呼叫 CoerceValue明確叫用,當 WPFWPF 屬性系統重新評估相依性屬性值時,也會在內部叫用相依性屬性的 CoerceValueCallbackIn addition to being explicitly invoked through calling CoerceValue, the CoerceValueCallback for a dependency property is also invoked internally whenever the dependency property value is being re-evaluated by the WPFWPF property system.

當您叫用 CoerceValue 方法時,您最後會叫用您指定之屬性的強制轉型值回呼。When you invoke the CoerceValue method, you are ultimately invoking the coerce value callback for the property that you specify. 通常只有在您知道強制轉型值回呼存在,而且您知道回呼的強制條件時,才會叫用 CoerceValueTypically you will invoke CoerceValue only if you know that a coerce value callback exists, and if you know the callback's criteria for coercion.

呼叫 CoerceValue 最常見的案例是在類別處理或屬性變更回呼的相關屬性中,以相依的方式影響彼此的值。The most common scenario for calling CoerceValue is within class handling or property change callbacks of related properties that influence each other's values in a dependent way. 如需詳細資訊,請參閱相依性屬性回呼和驗證For more information, see Dependency Property Callbacks and Validation.

Applies to

See also