2009-07-01 98 views
2

我试图为ComboBox编写我自己的验证规则,该规则附加到SelectedItem的绑定 - 但它没有工作。我有类似的规则工作Text属性...关于绑定的WPF验证 - 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不会出现一个依赖属性。

它通过包含TextProperty和SelectionBoxItemProperty但没有SelectedItemProperty的dependencyPropertyFields进行迭代。

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,因为组合框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

非常感谢您的工作! – 2009-07-01 16:09:30