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

与世无争的帅哥 提交于 2020-06-18 10:36:18

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!