How to limit special characters like% in a text box in wpf?

I would like to design a text box that restricts special characters like%. I used the keydown keydown event to limit the "%". I already used the code as

if(Keyboard.Modifiers == ModifierKeys.Shift && e.key == key.D5) { e.handle=true; return; } 

when I implement this in mvvm architecture, I had a problem with a dependency property that only recognizes the shift as one key and D5 as the other when I converted systemkey to string format.

How to recognize the% character?

+4
source share
1 answer

you can listen to the PreviewTextInput event instead of KeyDownEvent:

 myTextBox.PreviewTextInput += PreviewTextInputHandler; 

and then:

 private void PreviewTextInputHandler(Object sender, System.Windows.Input.TextCompositionEventArgs e) { e.Handled = !AreAllValidChars(e.Text); } 

this is one of the functions that I use in my application, you will have to tweak it a bit to check the correct characters, but you know how to do it.

as for getting% caracter, you just need to write something like:

 if (e.Text == '%') ...; 
+4
source

Source: https://habr.com/ru/post/1337936/


All Articles