我有一个用于在控件周围显示红色边框和错误消息的模板。它可以工作(在 TextBoxes 和 ComboBoxes 上测试)。但是在两个特定的组合框上却没有。
那么让我们看看VM中有什么不同:
- 因为我的基类中有通用的验证实现,所以没有改变
- 显示相同类型的异步加载数据,只需一个面板即可很好地进行验证
所以简而言之,VM没有区别。
视图完全一样,应用了相同的样式,所以总之也没有区别。
所以我添加NotifyOnValidationError=True
了ValidatesOnDataErrors=True
已经存在的内容,并订阅了Validation.Error
......它被解雇了!然而模板仍然没有显示。我没有想法,请建议我检查一下!
编辑:进一步研究:
我已经反编译了 DataErrorValidationRule,并将其重新编译为 MyDataErrorValidationRule 以尽可能接近原始匹配。我删除了ValidatesOnDataErrors=True
,并将我的 ValidationRule 添加到调试。它返回new ValidationResult(false, (object)str);
包含正确错误消息的 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 在同一个网格中。
唯一的区别是 SelectedItem 或 SelectedValue 是否被绑定,但这不应该对验证有任何影响......