C# WPF 如何在文本框中仅使用数值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42480514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 14:01:45  来源:igfitidea点击:

C# WPF How to use only numeric value in a textbox

c#wpfeventsnumeric

提问by GabelUndMesser

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.

我使用了一个 WPF 应用程序,我只想在文本框中允许数字。在 WindowsForm 应用程序中,我会知道我必须如何制作它。
不幸的是,WPF 中没有 KeyPress,并且“代码”也不再起作用。

How is it right and what is the event?

它是如何正确的,事件是什么?



Here you can see the old code that has worked in Windows Form:

在这里您可以看到在 Windows 窗体中工作的旧代码:

private void tbKreisdurchmesser_KeyPress(object sender, KeyEventArgs e)
{
    if (char.IsNumber(e.Key) || e.KeyChar==".")
    {

    }
    else
    {
        e.Handled = e.KeyChar != (char)Keys.Back;
    }
}

回答by Prajeesh T S

You can add Previewtextinput event for textbox and validate the value inside that event using Regex,

您可以为文本框添加 Previewtextinput 事件并使用正则表达式验证该事件中的值,

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