如何验证文本框应该只允许WPF中按键事件的整数和一个点

问题描述:

在按键时,我需要允许数字键盘和数字板上的唯一数字和一个点。



我尝试了什么:



At key down I need to allow the only digits and one dot through the both numberpad and digits board.

What I have tried:

if ((e.Key <= Key.D0 && e.Key >= Key.D9) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9))
{
    e.Handled = true;
    MessageBox.Show("I only accept numbers, sorry. :(");
}



plaese帮助我..


plaese help me..

请参考以下代码,

检查字符是否为数字的功能

Hi, just refer the following code,
Function to check whether a character is numeric or not
private bool AreAllValidNumericChars(string str)
{
    foreach (char c in str)
    {
        if (c != '.')
        {
            if (!Char.IsNumber(c)) return false;
        }
        else
        {
            if (textBox.Text.Contains(".") == true)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
    }

    return true;
}



只需在文本框的 PreviewTextInput 上调用此函数,如下所示,


Just call this function on PreviewTextInput of your textbox like below,

private void YourTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    e.Handled = !AreAllValidNumericChars(e.Text);
    base.OnPreviewTextInput(e);
}