J'ai essayé d'écrire ma propre règle de validation pour un ComboBox, la règle est attachée à la liaison pour SelectedItem - Cependant, cela ne fonctionne pas. J'ai des règles similaires travaillant sur la propriété Text ...WPF Validation sur la liaison - ComboBox SelectedItem ne va pas valider
<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>
Je pense que vers le bas au code que je utilise pour appeler la validation que j'ai trouvé sur le net. Fondamentalement SelectedItem ne vient pas une propriété de dépendance.
Il itère via dependencyPropertyFields qui contient TextProperty et SelectionBoxItemProperty mais pas 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;
}
}
}
}
}
ne sait de toute façon où je vais mal?
Toute aide grandement appréciée!
Merci,
Andy
Merci beaucoup pour cela, a travaillé un régal! –