Original address
http://blog.csdn.net/ghosind/article/details/51627601
Author Ghosind
One, the regular expression filters the string
if(Regexstring = =NULL){ Switch(constrainttype) { CaseRestricttype.int://integerRegexstring =@"^[-]? ([\d]+)? $"; Break; CaseRestricttype.uint://non-negative integersRegexstring =@"^[\d]+$"; Break; CaseRestricttype.double://floating point numberRegexstring =@"^[-]? ([0-9]+)? [.]? ([0-9]+)? $"; Break; CaseRestricttype.udouble://positive non-negative floating point numberRegexstring =@"^[0-9]+[.]? ([0-9]+)? $"; Break; CaseRestricttype.none://Unlimited default: regexstring=""; Break; }}
Second, the Previewtextinput event gets the full text of the textbox, (normal textbox.text is the text before the input)
if (! Regex.IsMatch (this. Text + E.text, regexstring)) { true;}
However, if the input is not added directly to the last party, this is used to Careindex property (the position of the current cursor).
if (! Regex.IsMatch (this. Text.insert (this. Caretindex, E.text), regexstring)) { true;}
However, if you select a text and then enter, the result is still wrong, so the original author uses a property selectionlength, select the length of the text
Finally, the method of getting all the text after the input is realized,
Private voidPreviewtextinput (Objectsender, TextCompositionEventArgs e) { Try { if(! Regex.IsMatch ( This. Text.remove ( This. Caretindex, This. Text.length >= This. Caretindex + This. SelectionLength? This. SelectionLength:0). Insert ( This. Caretindex, E.text), regexstring)) {e.handled=true; } } Catch(Exception) {}}
Third, using regular expressions to filter the input text, this web-based material is very much not copied, to the original people salute
WPF-developed controls for restricting input---------go from cdsn