DependencyProperty.IsValidValue(Object) Method


确定所提供的值通过基本类型检查后是否被属性类型接受,以及它是否有可能在该类型的值的允许范围以内。Determines whether the provided value is accepted for the type of property through basic type checking, and also potentially if it is within the allowed range of values for that type.

 bool IsValidValue(System::Object ^ value);
public bool IsValidValue (object value);
member this.IsValidValue : obj -> bool
Public Function IsValidValue (value As Object) As Boolean



要检查的值。The value to check.



如果值是可接受的,并且具有正确的类型或派生类型,则为 true;否则为 falsetrue if the value is acceptable and is of the correct type or a derived type; otherwise, false.


下面的示例在对依赖属性调用 SetValue 之前,使用 IsValidValue 作为检查。The following example uses IsValidValue as a check before calling SetValue on the dependency property.

void TrySetValueWithValidate(DependencyObject target, DependencyProperty dp, object providedValue)
  if (dp.IsValidValue(providedValue))
    target.SetValue(dp, providedValue);
Private Sub TrySetValueWithValidate(ByVal target As DependencyObject, ByVal dp As DependencyProperty, ByVal providedValue As Object)
  If dp.IsValidValue(providedValue) Then
    target.SetValue(dp, providedValue)
  End If
End Sub


对于依赖属性,可以通过依赖属性注册中提供的 ValidateValueCallback 指定该类型的值的允许范围。For a dependency property, an allowed range of values for that type can be specified through a ValidateValueCallback that is provided in the dependency property registration.

此方法在内部调用 IsValidTypeThis method calls IsValidType internally. 如果相关的依赖项属性没有 ValidateValueCallback,则调用此方法实际上等效于调用 IsValidTypeIf the dependency property in question has no ValidateValueCallback,then calling this method is effectively equivalent to calling IsValidType. 如果依赖属性具有 ValidateValueCallback,且 IsValidType 会返回 true,则返回的值将在回调中实现。If the dependency property does have a ValidateValueCallback, and if IsValidType would have returned true, then the value returned will be as implemented in the callback.

空值是引用类型依赖属性或 Nullable<T> 依赖属性的有效值,在这些情况下,将返回 trueA null value is a valid value for reference type dependency properties, or for a Nullable<T> dependency property, and would return true for these cases. 如果依赖属性既不是引用,也不是 Nullable<T> 类型,则 IsValidType 将为 null 值返回 false,而不是引发异常。In cases where the dependency property is neither a reference nor a Nullable<T> type, IsValidType will return false for a null value rather than raise an exception.

Applies to