I
I
Ivan2020-03-27 19:26:24
WPF
Ivan, 2020-03-27 19:26:24

How to limit certain characters in a TextBox in WPF?

How, for example, to make it possible to enter only numbers in the TextBox text field? Or vice versa, only letters. I was looking for information about this, I found a solution for WinForms. Tried like this option:

char number = e.KeyChar;
 
 if (!Char.IsDigit(number))
 {
    e.Handled = true;
 }

So is this one:
if (e.KeyChar <= 47 || e.KeyChar >= 58)
{
    e.Handled = true;
}


For WPF they didn't work

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
twobomb, 2020-03-27
@Vamba45

Should work, hang on the PreviewTextInput event and check not e.KeyChar, but e.Text
of type

public Window()
        {
            InitializeComponent();
            this.textBox.PreviewTextInput += new TextCompositionEventHandler(textBox_PreviewTextInput);
        }
 
        void textBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            if (!Char.IsDigit(e.Text,0)) e.Handled = true;
        }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question