WPF limits the contents of a TextBox entry

Source: Internet
Author: User

Restricts the text box TextBox's input, which is applied in many scenarios. For example, in a text box, you can only enter 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "|" These 11 characters.

Restricting input 0-9 is easy to implement, and the key is this "|" Symbol. It corresponds to the Key.oempipe key in WPF. If the key is directly allowed to enter, then there will be "\" This symbol can also be entered. Then the question comes, how can we limit it? Simple: First make sure the SHIFT key is pressed.

The key code is as follows:

1 BOOL 0;

This allows the Key.oempiple key to be pressed to ensure that only the ' | ' is entered when we confirm that the SHIFT key has been pressed. Symbol.

A complete sample code is as follows:

1 Private voidTextbox_keydown_event (Objectsender, KeyEventArgs)2 {3             BOOLShiftkey = (Keyboard.modifiers & modifierkeys.shift)! =0;4             if(Shiftkey = =true)5             {6                 if(E.key! =key.oempipe)7                 {8e.handled =true;9                 }Ten             } One             Else if(E.key! = Key.delete && E.key! = Key.back && AE.key! = key.d0 && E.key! = key.d1 && -E.key! = Key.d2 && E.key! = key.d3 && -E.key! = key.d4 && E.key! = key.d5 && theE.key! = Key.d6 && E.key! = Key.d7 && -E.key! = Key.d8 && E.key! = key.d9 && -E.key! = key.numpad0 && E.key! = Key.numpad1 && -E.key! = key.numpad2 && E.key! = key.numpad3 && +E.key! = Key.numpad4 && E.key! = Key.numpad5 && -E.key! = Key.numpad6 && E.key! = Key.numpad7 && +E.key! = Key.numpad8 && E.key! =key.numpad9) A             { ate.handled =true; -             } -}

WPF limits the contents of a TextBox entry

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.