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;
}
}
}
}
}
无论如何知道我要去哪里错了吗?
任何帮助非常感谢!
感谢,
安迪
非常感谢您的工作! – 2009-07-01 16:09:30