wpf – How to make a textbox only receive numbers

Question:

How do I make a textbox receive only number, but only for WPF. With winform I can do it, but with WPF I still can't.

Answer:

You can use the TextBox PreviewTextInput event.

1. Layout (XAML)

Add the PreviewTextInput event to your TextBox:

<TextBox HorizontalAlignment="Left" Height="23" Margin="10,181,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" PreviewTextInput="TextBox_PreviewTextInput"/>

2. Code Behind (.cs)

Add the following using :

using System.Text.RegularExpressions;

Add the method to the PreviewTextInput event:

private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    var textBox = sender as TextBox;
    e.Handled = Regex.IsMatch(e.Text, "[^0-9]+");
}
Scroll to Top
AllEscort