Set the validationrules attribute of the binding to verify the binding.
<Stackpanel> <textbox X: Name = "txtage" fontsize = "30" foreground = "red"> </textbox> <textblock X: name = "errorsummary" fontsize = "30" foreground = "red"> </textblock>
</Stackpanel>
BackgroundCode
Public partial class mainwindow: window {public mainwindow () {initializecomponent (); person P = new person {age = 20, name = "Tom "}; binding binding = new binding ("Age") {source = p}; binding. notifyonvalidationerror = true; binding. updatesourcetrigger = updatesourcetrigger. propertychanged; rangevalidationrule Rv = new rangevalidationrule (); binding. validationrules. add (RV); this.txt age. setbinding (textbox. textproperty, binding); this.txt age. addhandler (validation. errorevent, new routedeventhandler (this. validationerror);} void validationerror (Object sender, routedeventargs e) {If (validation.geterrors(this.txt age ). count> 0) {this.txt age. tooltip = validation.geterrors(this.txt age) [0]. errorcontent. tostring (); this. errorsummary. TEXT = validation.geterrors(this.txt age) [0]. errorcontent. tostring ();
// You can do everything here when validation error occurs }}}}
Similarly, we can set verification in XAML.
<Stackpanel> <textbox X: Name = "txtage" fontsize = "30" foreground = "red" validation. error = "txtage_error"> <binding parameter yonvalidationerror = "true" Path = "Age" updatesourcetrigger = "propertychanged"> <binding. validationrules> <local: rangevalidationrule> </binding. validationrules> </binding> </textbox> <textblock X: Name = "errorsummary" fontsize = "30" foreground = "red"> </textblock> </stackpanel>
Background code:
Public partial class mainwindow: window {public mainwindow () {initializecomponent (); person P = new person {age = 20, name = "Tom"}; this. datacontext = P;} private void txtage_error (Object sender, validationerroreventargs e) {If (validation.geterrors(this.txt age ). count> 0) {this.txt age. tooltip = validation.geterrors(this.txt age) [0]. errorcontent. tostring (); this. errorsummary. TEXT = validation.geterrors(this.txt age) [0]. errorcontent. tostring (); // you can do everything here when validation error occurs }}