views:

79

answers:

0

I'm fairly new to WPF. In our current project, we've added validation rules for all data entry fields that we need validation for. We have also copied code (also posted elsewhere here at stackoverflow) that recursively loops over all bindings and their validation rules, in order to know whether or not all the data is valid before saving data.

This is our code that I think is the place to address our problem:

Public Function ValidateBindings(ByVal parent As DependencyObject) As Boolean
  Dim valid As Boolean = True
  Dim localValues As LocalValueEnumerator = parent.GetLocalValueEnumerator

  While localValues.MoveNext
   Dim entry As LocalValueEntry = localValues.Current
   If BindingOperations.IsDataBound(parent, entry.Property) Then
    Dim binding As Binding = BindingOperations.GetBinding(parent, entry.Property)
    For Each rule In binding.ValidationRules
     Dim result As ValidationResult = rule.Validate(parent.GetValue(entry.Property), Nothing)
     If Not result.IsValid Then
      Dim expression As BindingExpression = BindingOperations.GetBindingExpression(parent, entry.Property)
      Validation.MarkInvalid(expression, New ValidationError(rule, expression, result.ErrorContent, Nothing))
      valid = False
     End If
    Next
   End If
  End While

  For i As Integer = 0 To VisualTreeHelper.GetChildrenCount(parent) - 1
   Dim child As DependencyObject = VisualTreeHelper.GetChild(parent, i)

   If Not ValidateBindings(child) Then
    valid = False
   End If
  Next

  Return valid
 End Function

I've tried to find out how to use GetValue() on the IsEnabledProperty dependency property of the parent, but my attempts so far have failed. Can anybody help me with this or this not the correct way of thinking to solve this problem?

Alternatively, I've been playing with the thought of binding the validation error to a "ignore any content"-rule when the field is disabled, but it seems like more trouble to me.

I've tried to set Binding.NotifyOnValidationError through Binding in XAML, to bind to to the same value for the element's IsEnabled and NotifyOnValidationError but I cannot do that since it is not a DependencyProperty.

Another thing I tried was to add a property ElementIsEnabled in the validation class, do be able to do something like this in XAML:


    <Binding.ValidationRules>
        <local:MustContainInteger ElementIsEnabled="{Binding SameBindingAsIsEnabled}" />
     </Binding.ValidationRules>

But that also fails since ElementIsEnabled is not a DependencyProperty on a DependencyObject.

Anyway, any help on this would be greatly appreciated.