There is a problem in .NET 4.0, which does not exist in 3.5 (have not tested earlier or later frameworks).
I have created a demo user control, which has only a single property Num (of type Integer):
Public Class UserControl1
Public Shared NumProperty As DependencyProperty = _
DependencyProperty.Register("Num", _
GetType(Integer), _
GetType(UserControl1), _
New PropertyMetadata(defaultValue:=0, _
PropertyChangedCallback:=New PropertyChangedCallback(AddressOf OnNumPropertyChanged), _
CoerceValueCallback:=New CoerceValueCallback(AddressOf OnNumPorpertyCoerce)), _
New ValidateValueCallback(AddressOf IsNumValid))
Public Property Num As Integer
Get
Return GetValue(NumProperty)
End Get
Set(value As Integer)
SetValue(NumProperty, value)
End Set
End Property
Public Shared Function IsNumValid(value As Object) As Boolean
If value IsNot Nothing And TypeOf value Is Integer Then
If CInt(value) < 0 Then
Return False
End If
End If
Return True
End Function
Public Shared Sub OnNumPropertyChanged(sender As DependencyObject, e As DependencyPropertyChangedEventArgs)
' do nothing here
End Sub
End Class
So, basically, you can not set anything smaller than zero to Num.
The question
When I use this control in WPF window and try to set Num=-1, I get the exception.
However if I try to use this control as part of DataTemplate, and also set Num=-1, there is no excepetion raised.
I have tried to put a breakpoint in Validation procedure of my user control, but it is hit only in case of user control in window, and it is not hit if I have user control in DataTemplate.
Can anybody explain why validation is not executed from DataTemplate?
P.S. you can find related thread on Microsoft’s forums: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/f7fd05a5-cae3-496a-8abe-590541ecdd0a
While Microsoft solves this problem (upvote at https://connect.microsoft.com/VisualStudio/feedback/details/742083/dependencyproperty-validation-is-not-called-from-data-template), workaround may be used:
In your coercion function call validation function (leave validation function for all those cases then it is called). And if the validation result is False, raise an System.ArgumentException with a message of such pattern: ‘%INVALID VALUE%’ is not a valid value for property ‘%PROPERTY_NAME%’. By providing such code you will provide user of your user control with same information he or she would get from regular validation.