问题
I use a WPF application I would like to allow only numbers in a textbox. In a WindowsForm application I would know how I would have to make it.
Unfortunately, there is a KeyPress not in WPF and the "code" functioned also no longer.
How is it right and what is the event?
Here you can see the old code that has worked in Windows Form:
private void tbKreisdurchmesser_KeyPress(object sender, KeyEventArgs e)
{
if (char.IsNumber(e.Key) || e.KeyChar==".")
{
}
else
{
e.Handled = e.KeyChar != (char)Keys.Back;
}
}
回答1:
You can add Previewtextinput event for textbox and validate the value inside that event using Regex,
private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
var textBox = sender as TextBox;
e.Handled = Regex.IsMatch(e.Text, "[^0-9]+");
}
来源:https://stackoverflow.com/questions/42480514/c-sharp-wpf-how-to-use-only-numeric-value-in-a-textbox