我有一个模板,用于在控件周围显示红色边框和错误消息。它可以在TextBox和ComboBox上正常工作,但在两个特定的ComboBox上却不行。
那么让我们看看VM中有什么不同:
- 由于我在基类中具有通用验证实现,因此没有变化
- 显示相同类型的异步加载数据,仅使用一个面板的验证正常工作
所以简而言之,VM中没有任何区别。
视图完全相同,应用了相同的样式,因此简而言之,在这方面没有任何区别。
所以我添加了NotifyOnValidationError=True
到已经存在的ValidatesOnDataErrors=True
,并订阅了Validation.Error
...... 然后它被触发了!但是模板仍然没有显示出来。 我没有主意了,请建议我要检查的事情!
编辑:进一步研究:
我反编译了DataErrorValidationRule,并重新编译为MyDataErrorValidationRule,尽可能接近原始版本。我删除了ValidatesOnDataErrors=True
,并添加了我的ValidationRule进行调试。它返回带有正确错误消息的str两次的new ValidationResult(false, (object)str);
- 一次是将属性设置为null,另一次是强制验证整个对象。 模板仍然没有显示。
我还检查了控件上的Validation.GetErrorTemplate(在第一次触发Validation.Error时),它不是NULL,因此也不是DynamicResource出错了。
编辑:工作示例:
<ItemsControl ItemsSource="{Binding QuestionAnswers}">
<ItemsControl.Resources>
<!-- ... -->
<DataTemplate DataType="{x:Type Model:QuestionAnswerModel}">
<StackPanel>
<!-- here is the combo box -->
<ComboBox Margin="8,4" Padding="8" MinWidth="120" HorizontalAlignment="Left"
Validation.ErrorTemplate="{DynamicResource DefaultValidationErrorTemplate}"
ItemsSource="{Binding Options.Source}"
DisplayMemberPath="ItemName" SelectedValuePath="ItemID"
SelectedValue="{Binding Options.SelectedID, ValidatesOnDataErrors=true}" />
</StackPanel>
</DataTemplate>
</ItemsControl.Resources>
</ItemsControl>
错误示例:
<ComboBox Margin="8,4" Padding="8" MinWidth="120" HorizontalAlignment="Left"
Validation.ErrorTemplate="{DynamicResource DefaultValidationErrorTemplate}"
SelectedItem="{Binding Type.SelectedItem, ValidatesOnDataErrors=True, NotifyOnValidationError=True}" Validation.Error="ComboBox_Error"
ItemsSource="{Binding Type.Source}"
DisplayMemberPath="Localized"
>
它们来自于同一个XAML文件,包含工作ComboBox的ItemsControl与不工作的ComboBox在同一个Grid中。
唯一的区别是绑定的是SelectedItem还是SelectedValue,但这不应该对验证造成任何影响...