WPF validation - ValidatesOnTargetUpdated

☆樱花仙子☆ 提交于 2019-12-12 15:21:20

问题


I have a number of textboxes in a WPF app on which I have set up some validation.

On load the app deserialises a class onto which the WPF window's controls are bound.

I have a ValidationRule that (for example) tests that a file exists. If I don't set ValidatesOnTargetUpdated then the corresponding TextBox validates when I change the (bound) Text Property and I see the (default) red border appear and a Tooltip ({Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors).CurrentItem.ErrorContent}) displaying the error message.

I want the controls to validate on binding rather than on propertychanged so I have set the ValidatesOnTargetUpdated to true and can see the validationRule firing when debugging.

My problem is that the (default) ValidationTemplate is ignored when ValidatesOnTargetUpdated="True" despite the ValidationRule firing.

I can see the Tooltip - it appears with the correct error message but the border doesn't show as Red; this seems to be ignored.

Any ideas why this would be happening?


回答1:


You may want to read this forum post. I believe the part that pertains to your situation is:

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.

EDIT:

A more permanent link can be found here.



来源:https://stackoverflow.com/questions/5940478/wpf-validation-validatesontargetupdated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!