WPF uses IDataErrorInfo for data validation

Source: Internet
Author: User

This blog will show you how to use IDataErrorInfo for data validation. Take a look at the example below. A customer class, two attributes (FirstName, age)

class customer{    publicstring  FirstName    {        get;         Set ;    }      Public int Age    {        get;         Set ;    }}

Inherit the customer class IDataErrorInfo and implement its properties.

    classCustomer:System.ComponentModel.IDataErrorInfo { Public string  This[stringColumnName] {            Get            {                stringresult =string.                Empty; if(ColumnName = ="FirstName")                {                    if(string. Isnullorwhitespace (FirstName)) {result="Name cannot null or empty."; }                }                Else if(ColumnName = =" Age")                {                    if(Age <0) {result="Age cannot and then zero."; }                }                returnresult; }        }         Public stringError {Get            {                return NULL; }        }         Public stringFirstName {Get; Set; }         Public intAge {Get; Set; }    }

Binds the Firstname,age property of the customer in the UI and triggers validation when the error data occurs.

<Window.Resources> <local:customer x:key="customerinstance"Firstname="Sam Bent"Age=" -"/> <controltemplate x:key="textboxerrortemplate"> <Grid> <border borderbrush="Blue"borderthickness="1"> <AdornedElementPlaceholder/> </Border> </Grid> </ControlTemplate> </Window.Resources> <stackpanel margin="Ten"> <TextBox Text="{BindingSource={StaticResource customerinstance}, Path=FirstName, UpdateSourceTrigger=propertychanged, validatesondataerrors =true} " tooltip="{Binding relativesource={relativesource self}, path= (Validation.errors) [0]. Errorcontent}"  validation.errortemplate="{x:null}"Margin="0,5"/> <textbox text="{BindingSource={StaticResource customerinstance}, Path=Age , UpdateSourceTrigger=propertychanged, validatesondataerrors =true}"            validation.errortemplate="{StaticResource textboxerrortemplate}" ><TextBox.Style> <style targettype="{x:type TextBox}"> <Style.Triggers> <trigger property="Validation.haserror"Value="True"> <setter property="Background"Value="Red"/> <setter property="ToolTip"Value="{Binding Relativesource={relativesource self}, path= (Validation.errors) [0]. Errorcontent}"/> </Trigger> </Style.Triggers> </Style> </TextBox.Style></TextBox> </StackPanel>

The FirstName of the customer is bound to the Age property in two TextBox respectively, and the validatesondataerrors=true is set to trigger the validation. Bind the error message to the ToolTip property of the TextBox,

tooltip= "{Binding relativesource={relativesource self}, path= (validation.errors) [0]. Errorcontent} "or

tooltip= "{Binding relativesource={relativesource self}, path= (validation.errors). Currentitem.errorcontent} " or

<StyleTargetType= "{x:type TextBox}">    <style.triggers>        <Trigger Property= "Validation.haserror"Value= "True">            <Setter Property= "Background"Value= "Red" />            <Setter Property= "ToolTip"Value= "{Binding relativesource={relativesource self}, path= (Validation.errors) [0]. Errorcontent} " />        </Trigger>    </style.triggers></Style>

Errortemplate can also be customized, such as the textboxerrortemplate in the code above.

Operation Result:

Code click here to download, thank you for reading.

WPF uses IDataErrorInfo for data validation

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.