2009-07-01 8 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

大変ありがとうございました。 –

関連する問題