Title, there are many ways to do this, and if you are using the development mode of MVVM, how do you implement this feature? As simple as creating a new attached property for a textbox, this problem can be solved perfectly.
Create a new Attachment property, Isonlyacceptfigure, and add the property callback function to it.
The code is as follows:
namespaceWPF. validation{ Public classTextboxonlyacceptfigurebehavior { Public Static ReadOnlyDependencyProperty Isonlyacceptfigureproperty =dependencyproperty.registerattached ("isonlyacceptfigure",typeof(BOOL), typeof(Textboxonlyacceptfigurebehavior),NewUIPropertyMetadata (false, onbindedpasswordchanged)); Public Static BOOLgetisonlyacceptfigure (DependencyObject obj) {return(BOOL) obj. GetValue (Isonlyacceptfigureproperty); } Public Static voidSetisonlyacceptfigure (DependencyObject obj,BOOLvalue) {obj. SetValue (isonlyacceptfigureproperty, value); } Private Static voidonbindedpasswordchanged (DependencyObject obj, DependencyPropertyChangedEventArgs e) {
varTextBox = obj asTextBox; if(TextBox = =NULL) return; if((BOOL) {e.newvalue) {textbox.previewtextinput+=Textbox_previewtextinput; Textbox.previewkeydown+=Textbox_previewkeydown; Dataobject.addpastinghandler (TextBox, textbox_pasting); } Else{textbox.previewtextinput-=Textbox_previewtextinput; Textbox.previewkeydown-=Textbox_previewkeydown; Dataobject.removepastinghandler (TextBox, textbox_pasting); } } Private Static voidTextbox_pasting (Objectsender, Dataobjectpastingeventargs e) { if(E.dataobject.getdatapresent (typeof(string))) { varText = (string) E.dataobject.getdata (typeof(string)); if(!isnumberic (text)) {E.cancelcommand (); } } Else{E.cancelcommand (); } } Private Static voidTextbox_previewkeydown (Objectsender, KeyEventArgs e) { if(E.key = =key.space) e.handled=true; } Private Static voidTextbox_previewtextinput (Objectsender, TextCompositionEventArgs e) {e.handled= !isnumberic (E.text); } Public Static BOOLIsnumberic (string_string) { if(string. IsNullOrEmpty (_string))return false; return_string. All (Char. IsDigit); } }}
How to Invoke:
<textbox local:textboxonlyacceptfigurebehavior.isonlyacceptfigure="True"/>
PS: Verify that the input code comes from the network, again thanks to the user to share.
I wish you a happy life!
[. NET] Implementation in WPF TextBox can only enter numbers