C#WPF如何在文本框中仅使用数字值 [英] C# WPF How to use only numeric value in a textbox

查看:254
本文介绍了C#WPF如何在文本框中仅使用数字值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的WPF应用程序只允许在文本框中输入数字.在WindowsForm应用程序中,我会知道该怎么做.
不幸的是,WPF中没有KeyPress,代码"功能也不再存在.

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?

在这里您可以看到在Windows窗体中运行过的旧代码:

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;
    }
}

推荐答案

您可以为文本框添加Previewtextinput事件,并使用Regex验证该事件中的值,

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]+");
}

这篇关于C#WPF如何在文本框中仅使用数字值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆