Data validation in WPF

Source: Internet
Author: User

The binding of WPF enables data to flow between data sources and targets, allowing data to be processed in the middle of the flow of data.
数据转换And it is the 数据验证 validation and conversion of data from the source to the target or from the target to the source.

ValidationRule validation Rules

WPF provides an abstract class in which ValidationRule our custom validation rules need to inherit it and then implement its abstraction
Method Validate , which needs to return a Validationresult object to represent the validation result. As an example, a verification number
The rules (only numbers are entered)

PublicClassnumbervalidationrule: validationrule {public override Validationresult validate (object value, CultureInfo CultureInfo) {if (Regex.IsMatch (value. ToString (),  "^[0-9]+$")) {return  New Validationresult (true, null);} else {return new Validationresult (false,  "Enter Number"),}}}      

The two attributes of which ValidationRule

    • validatesontargetupdated

      This property can determine the direction of validation and, if set to false, only validates the direction from the target to the source, if true,
      It also verifies the direction from source to destination

    • ValidationStep
      This property determines the timing of the validation, which is an enumeration value
      1 Committedvalue, after the value is committed to the data source, runs ValidationRule, that is, the property will be updated regardless of whether the validation passes
      2 Convertedproposedvalue, after the conversion, run the ValidationRule, if there is data conversion, then the first conversion re-authentication
      3 Rawproposedvalue, before any conversions occur, run ValidationRule
      4 Updatedvalue, after updating the source, run ValidationRule, that is, after the property value is changed, will be verified, note the need to
      ValidatesOnTargetUpdatedSet to True

It is also important to note that the binding's handling of the validation results is NotifyOnValidationError set to True when validation occurs
Error, the error message goes up from the target along the visual tree 冒泡 until the bubbling event is heard and processed.

   <Textboxgrid.row="1" ><Textbox.text><BindingPath="Number"Updatesourcetrigger="PropertyChanged"Converter=  "{StaticResource Converter}" notifyonvalidationerror= "True" > <binding.validationrules> Span class= "Hljs-tag" ><validationrules:numbervalidationrule  Validatesontargetupdated= "True" validationstep=" Committedvalue "></validationrules: numbervalidationrule> </binding.validationrules> </binding> </ textbox.text> </TEXTBOX>      

When a validation error occurs, the textbox will have a red box, which is the default error template style, how do we define an error template (errortemplate)?

Error template Errortemplate
   <ControlTemplatex:key="Errortemplate" ><StackPanelorientation="Horizontal" ><AdornedelementplaceholderX:name="Placeholder" ></Adornedelementplaceholder><TextBlockForeground="Red"text= "{Binding elementname=placeholder,path=adornedelement. Validation.errors) [0]. Errorcontent} "fontsize=" x:Name=< Span class= "hljs-string" > "txt" ></textblock> </stackpanel> </ controltemplate> <textbox Grid.Row=  "1" height= "30" width= "all" validation.errortemplate=  "{StaticResource errortemplate}";         

Adornedelementplaceholder represents a placeholder, which indicates that the specific control is a textbox, which indicates that the layout of the error template is
If there is a validation error, there will be a TextBlock text in the back of the textbox, and the content of the text displays the information of the validation error.

Validation

This involves a class Validation , which is a static class that is mostly used with attached properties. Its main function is to
1 Setting Errortemplate
2 Determine if there is an error (HASERROR), and get the list of errors (Errors)
3 Listening for validation error events

The first two points are mentioned earlier, now look at the Listen validation error bubbling Event

<Gridgrid.row="1"Validation.error="Validation_onerror" ><Textboxheight="30"Width="100"Validation.errortemplate="{StaticResource errortemplate}" ><Textbox.text><BindingPath="Number"Updatesourcetrigger="PropertyChanged"Notifyonvalidationerror="True" ><binding.validationrules> <validationrules:numbervalidationrule></ validationrules:numbervalidationrule> </ binding.validationrules> </binding> </textbox.text> </ textbox> </Grid> private void Validation_onerror (object sender, Validationerroreventargs e) {if (e.action = = validationerroreventaction.added) {// TODO: New validation error _errormessage = E.error.errorcontent.tostring (); } else {//todo: Clears the original error _errormessage = string. Empty; } }

The only thing to notice here is ValidationErrorEventAction This enumeration value because of the new validation error, and the purge
This event is triggered by the original validation error, so it needs to be distinguished.
At this point, data validation in WPF is almost there.

Data validation in WPF

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.