Managing the input in your project is very important. In this post, you can see how create a numeric field in WPF, using the regular expressions.
XAML:
<TextBox PreviewTextInput="NumberValidationTextBox"></TextBox>
Code behind:
private void NumberValidationTextBox(object sender, TextCompositionEventArgs e) { Regex regex = new Regex("[^0-9]+"); e.Handled = regex.IsMatch(e.Text); }
If you also want to set the max length of this field, you can simply use the attribute maxLenght:
<TextBox MaxLength="5" PreviewTextInput="NumberValidationTextBox"></TextBox>
1 January 2019 at 21:47
Plese say where to put the code behind part. Thank you in advance.
LikeLiked by 1 person
22 March 2019 at 6:47
Unfortunately, this doesn’t prevent the user from pasting invalid text via CTRL+V, since this doesn’t trigger PreviewTextInput
@Dusan: The code behind is placed inside the .xaml.cs file
LikeLike
15 March 2021 at 17:50
@cpfr, is there a way or a line of code that can stop the user from pasting invalid text? Any ideas?
LikeLike
9 August 2021 at 16:54
custom pasting handler, or just disable it
LikeLike
9 August 2021 at 17:23
TextBox.CommandBindings.Add(new(ApplicationCommands.Paste, (sender, e) => e.Handled = true));
Something like this should do the trick.
Also, make sure to stop user from typing spaces too, can be done with preview key down
LikeLike