2009-07-01 1 views
2

Я попытался написать свое собственное правило валидации для ComboBox, правило привязано к привязке для SelectedItem - однако это не работает. У меня есть аналогичные правила, работающих на свойстве Text ...WPF Validation on Binding - ComboBox SelectedItem не будет проверять

<ComboBox VerticalAlignment="Top" ItemsSource="{Binding Animals}" DisplayMemberPath="Name" > 
     <ComboBox.SelectedItem> 
      <Binding Path="Animal"> 
       <Binding.ValidationRules> 
        <validators:ComboBoxValidationRule ErrorMessage="Please select an animal" /> 
       </Binding.ValidationRules> 
      </Binding> 
     </ComboBox.SelectedItem> 
    </ComboBox> 

Я думаю, что его вниз к коду я использую для вызова проверки, который я нашел в сети. В принципе SelectedItem не подходит для свойства зависимостей.

Он перебирает через dependencyPropertyFields, который содержит TextProperty и SelectionBoxItemProperty, но не SelectedItemProperty.

private void ValidateBindings(DependencyObject element) 
    { 
     Type elementType = element.GetType(); 

     FieldInfo[] dependencyPropertyFields = elementType.GetFields(
      BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly); 


     // Iterate over all dependency properties 
     foreach (FieldInfo dependencyPropertyField in dependencyPropertyFields) 
     { 
      DependencyProperty dependencyProperty = 
       dependencyPropertyField.GetValue(element) as DependencyProperty; 

      if (dependencyProperty != null) 
      { 


       Binding binding = BindingOperations.GetBinding(element, dependencyProperty); 


       BindingExpression bindingExpression = BindingOperations.GetBindingExpression(element, dependencyProperty); 

       // Issue 1822 - Extra check added to prevent null reference exceptions 
       if (binding != null && bindingExpression != null) 
       { 


        // Validate the validation rules of the binding 
        foreach (ValidationRule rule in binding.ValidationRules) 
        { 
         ValidationResult result = rule.Validate(element.GetValue(dependencyProperty), 
          CultureInfo.CurrentCulture); 

         bindingExpression.UpdateSource(); 

         if (!result.IsValid) 
         { 
          ErrorMessages.Add(result.ErrorContent.ToString()); 
         } 

         IsContentValid &= result.IsValid; 
        } 
       } 
      } 
     } 
    } 

В любом случае, знаете, где я иду не так?

Любая помощь очень ценится!

Спасибо,

Энди

ответ

3

Вы не нашли SelectedItemProperty, потому что ComboBox doesn't have поле SelectedItemProperty, вместо этого он наследуется, что от его базового класса Selector. Конечно, Selector и ComboBox не имеют всех свойств, которые вы могли бы связать с ними, вам нужно пройти весь путь до UIElement, чтобы найти большинство унаследованных свойств.

Если вы вставляете что-то, чтобы пересечь иерархию наследования, вы можете получить все поля, и будет выполнено правило проверки.

List<FieldInfo> dependencyPropertyFields = elementType.GetFields(
    BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly).ToList(); 

// Iterate through the fields defined on any base types as well 
Type baseType = elementType.BaseType; 
while (baseType != null) 
{ 
    dependencyPropertyFields.AddRange(
     baseType.GetFields(
      BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly)); 

    baseType = baseType.BaseType; 
} 
+0

Большое спасибо за это, сработало удовольствие! –