I have a WPF textbox that is databound. I need to restrict the user input on the textbox so that it only accepts numbers and a single period (For displaying decimals).
I know I can handle this in “Winforms” way and validate each input on KeyPress event, but I was wondering if there was a cleaner and maybe even proper way to do this in WPF (especially since I am databinding the textbox).
Use ValidationRules provided by WPF.
The xaml would be:
The code for the textbox property would be (used regex for the validation):
Source: Validation in WPF
The regex given above:
^((?:[1-9]\d*)|(?:(?=[\d.]+)(?:[1-9]\d*|0)\.\d+))$can be tested at this Rubular linkThe regex would match these:
but not these: (you could tweak the regex to allow some of them)