I am using WPF, MVVM-Light. In my UI I have a textbox, and I want to prevent the user from typing certain characters in the textbox. I know if we use code-behind I could handle the key down keyPress events, can I achieve it through MVVM? Can we use some behaviors or some interactivity triggers?
2 Answers
Using code-behind is perfectly OK with MVVM providing the code-behind is related to your View only.
So if you have some view-specific logic that says "User can only type numbers in this box", then it's perfectly OK to write a KeyPress
event for the TextBox
that only allows numeric keys to be processed. You could even throw this into a UserControl
so it can be reusable.
However if your allowed character logic is based on application logic, such as "User can only use the characters defined in the app.config file for this string value", then you'd be better off validating that in the ViewModel.
Also note that restriction is different from validation.
If you want to validate a user's entry, then I would do so using IDataErrorInfo
from the ViewModel layer, and possibly a binding with a mode of UpdateSourceTrigger=PropertyChanged
so the validation is checked after every key press.
If you want to restrict what characters can be typed into a TextBox
, then I would probably do that from the View layer in the code behind, as that is a functionality of the View.

- 130,264
- 66
- 304
- 490
Yes, to filter input the MVVM way, I would suggest either using a custom control (such as a masked TextBox
control) or a Behavior.
I was recently looking for a good masked TextBox
and there is a free one out there from Xceed which you can find here. I can't speak to this one, as I haven't used it, but I've been happy with other Xceed components I've used in the past.
However I didn't want to go third party and include a bunch of controls I didn't need, so I ended up creating a behavior that simply attaches to the TextBox
and filters the input based on a FilterType. The behavior is pretty easy to create, and you simply use the PreviewTextInput
event to filter out characters that you don't want.
This SO Answer has a number of suggestions and links to how to filter/mask the input and if you're not familiar with creating Attached Behaviors, this example shows how to create an Attached Behavior for a Masked Text Box.