WPF 验证 - ValidatesOnTargetUpdated

标签 wpf validation textbox validationrules

我在 WPF 应用程序中有许多文本框,我已在这些文本框上设置了一些验证。

加载时,应用反序列化 WPF 窗口控件绑定(bind)到的类。

我有一个 ValidationRule(例如)测试文件是否存在。如果我没有设置 ValidatesOnTargetUpdated,那么相应的 TextBox 会在我更改(绑定(bind))文本属性时进行验证,并且我会看到(默认)红色边框出现和工具提示({Binding RelativeSource={x:Static RelativeSource.Self} , Path=(Validation.Errors).CurrentItem.ErrorContent}) 显示错误信息。

我希望控件在绑定(bind)时进行验证,而不是在 propertychanged 时进行验证,因此我将 ValidatesOnTargetUpdated 设置为 true,并且可以在调试时看到 validationRule 触发。

我的问题是,尽管触发了 ValidationRule,但当 ValidatesOnTargetUpdated="True" 时,(默认)ValidationTemplate 被忽略了。

我可以看到工具提示 - 它显示正确的错误消息,但边框不显示为红色;这似乎被忽略了。

知道为什么会发生这种情况吗?

最佳答案

您可能想阅读此 forum post .我认为与您的情况有关的部分是:

Problem: The Error Template is not Displayed when a Page is Loaded

This is by design, since one could assume that the user doesn't want to see error messages before he/she made any mistakes, but sometimes one needs this functionality. So, the ValidatesOnTargetUpdated property was introduced on the ValidationRule class; by setting it to true, one sees the validation result immediately. However, there is one caveat: you must make sure that you set the DataContext after the page is initialized; this would be either in the constructor after the generated comment line that says that initialization code should go there, or in the Loaded event. If you want to set the DataContext in XAML, you find a solution for this problem here: http://wpfglue.wordpress.com/2009/12/08/navigating-from-object-to-object/

However, I hear this will be fixed in WPF 4.0.

编辑:

可以找到更永久的链接here .

关于WPF 验证 - ValidatesOnTargetUpdated,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5940478/

相关文章:

c# - 将值(int)设置为检查单选按钮 wpf

JavaScript - 从函数中获取返回值

javascript - 如何使用 JavaScript/HTML 通过下拉菜单和文本框定向 URL

C# wpf 列表框未从 ObservableCollection 更新

wpf - 在列表框中填充网格宽度

c# - 使用 John Myczek 类的水印

javascript - 快速验证器检查输入是否是可用选项之一

c++ - 只允许在程序中使用选择的字母(字符串)?

javascript - 如何限制特殊字符和 (/,*,+) only

c# - 将光标设置在文本框的任何文本的末尾