TextBox in WPF adds input detection, error prompt

Source: Internet
Author: User

To summarize the key points of implementing the error prompt function

1:binding's Validationrules

2:validation.errortemplate

First we add a textbox to the interface, the text bound to the property of the People object, age

public class people
{
public int Age {get; set;}
public string name {get; set;}
}

        <TextBoxx:name= "TextBox"HorizontalAlignment= "Left"Height= "+"Margin= "75,35,0,0"textwrapping= "Wrap"VerticalAlignment= "Top"Width= "155">            <TextBox.Text>                <BindingUpdateSourceTrigger= "PropertyChanged"Source="{StaticResource people}"Path= "Age" >                    <Binding.validationrules>                        <Local:agevalidationrule></Local:agevalidationrule>                    </Binding.validationrules>                </Binding>            </TextBox.Text>        </TextBox>

Here we binding. Validationrules Add a self-written error validation rule Agevalidationrule code as follows

Public     class Agevalidationrule:validationrule    {public        override Validationresult Validate (object Value, CultureInfo CultureInfo)        {            int ret = 0;            if (!int. TryParse (value. ToString (), out ret))                return new Validationresult (false, "not a valid number");            if (ret >130 | | ret<1)                return new Validationresult (false, "age must be between 1-130");            return new Validationresult (True, "");        }    }

Thus, when the value of text changes, it triggers the validation rule of the binding and invokes the Validate function in the face. The first parameter of the function value is the value of our binding, the second is the time zone information, here we do not have to control the second one.

At this point, our TextBox already has the ability to self-check. For example, enter a, a is not a number, when the Validate function is triggered, the validation returns an error message

Validationresult (False, "not a valid number")

You can see the box turn red. This is because the textbox comes with the default errortemplate.

Such hints are not obvious enough to reach our requirements.

Let's do it ourselves. A bug prompt template

            <validation.errortemplate>                <ControlTemplate>                    <StackPanelOrientation= "Horizontal">                        <AdornedelementplaceholderName= "Customadorner"></Adornedelementplaceholder>                        <TextBoxText="{Binding Elementname=customadorner, path=adornedelement. Validation.errors) [0]. Errorcontent}"Margin= "10,0,0,0"BorderBrush= "Red"Foreground= "Red"verticalcontentalignment= "Center" >                        </TextBox>                    </StackPanel>                </ControlTemplate>            </validation.errortemplate>

Analyze the code here, Validation.errortemplate, as an additional property, tied to a TextBox, when the textbox text changes, triggering the binding validation rule validationrules. Will call into the corresponding validate function inside.

If the function returns the result as an error. Then the errortemplate will show up.

There is a very interesting control adornedelementplaceholder in Errortemplate, which represents the host of the entire errortemplate. Suppose I have a control called XXX, set the errortemplate of XXX to the above errortemplate. Then this adornedelementplaceholder represents the xxx control. In this way, my errortemplate can locate the textbox in StackPanel and errortemplate according to the position of the xxx control.

That's where my error content is located.

Well, we see that the TextBox can set its own attached property validation.errortemplate, which should say that the entire validation can be considered an attached property of the textbox. So there's something we can use in this validation.

When the bingding validation is triggered, the error message is saved to the validation errors list. In this way, we can take out the error message inside. That is, the age at which the Validate function returns must be between 1-130.

So, we bind the text of the textbox with the error hint to its adornedelementplaceholder corresponding control. (validation.errors) [0]. Errorcontent

text= "{Binding elementname=customadorner, path=adornedelement. Validation.errors) [0]. Errorcontent} "

So far, done.

Take a look at the effect

Source Path: Https://files.cnblogs.com/files/CSSZBB/TextBoxErrorHint.zip

TextBox in WPF adds input detection, error prompt

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.