如何在WPF中强制文本框仅接受数字?

27

我希望用户只能在 TextBox 中输入数字。

我得到了这段代码:

private void txtType1_KeyPress(object sender, KeyPressEventArgs e)
{
     int isNumber = 0;
     e.Handled = !int.TryParse(e.KeyChar.ToString(), out isNumber);
}

使用WPF时,我没有收到textbox_KeyPress事件和e.KeyChar,该怎么办?

在WPF中有什么解决方案吗?

编辑:

我找到了一个解决方案!

private void txtName_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    CheckIsNumeric(e);
}

private void CheckIsNumeric(TextCompositionEventArgs e)
{
    int result;

    if(!(int.TryParse(e.Text, out result) || e.Text == "."))
    {
        e.Handled = true;
    }
}

明白了,非常有帮助。它起作用了... - Falcon
您可以在此处找到有关此问题的很好的答案概述。 - Pinotek
8个回答

18
protected override void OnPreviewTextInput(TextCompositionEventArgs e)
    {
        char c = Convert.ToChar(e.Text);
        if (Char.IsNumber(c))
            e.Handled = false;
        else
            e.Handled = true;

        base.OnPreviewTextInput(e);
    }

4
好的回答!不过,我会将你方法体内除了最后一行之外的所有内容替换为e.Handled = !Char.IsNumber(Convert.ToChar(e.Text)); - Anna Lam
10
PreviewTextInput()方法无法捕捉到空格键的按下事件。在PreviewKeyDown()中添加条件判断语句 if (e.Key == Key.Space) e.Handled = true; 可以解决这个问题。 - Igor
2
这个答案并没有解决用户将值粘贴到文本框中的问题。粘贴的值可能包含字母。 - dcp

8

1

你可以将文本框与依赖属性绑定,在依赖属性的验证方法中,你可以检查 int.tryparse 是否返回 true,如果是,则正常处理,否则可以选择默认值或重置值。

或者你可以使用 WPF ValidationRules 来查找值何时被更改。一旦更改,你可以应用逻辑进行输入验证。

或者你可以使用 IDataErrorInfo 进行验证。


1

Hasib Uz Zaman的位增强版本

     private void txtExpecedProfit_PreviewTextInput_1(object sender, TextCompositionEventArgs e)
    {
        CheckIsNumeric((TextBox)sender,e);
    }

    private void CheckIsNumeric(TextBox sender,TextCompositionEventArgs e)
    {
        decimal result;
        bool dot = sender.Text.IndexOf(".") < 0 && e.Text.Equals(".") && sender.Text.Length>0;
        if (!(Decimal.TryParse(e.Text, out result ) || dot )  )
        {
            e.Handled = true;
        }
    }

这将检查重复的小数点,并且不允许只有一个小数点。


1
//Call this code on KeyDown Event
if((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || (e.Key == Key.Back))
{ e.Handled = false; }
else if((e.Key >= Key.D0 && e.Key <= Key.D9))
{ e.Handled = false; }
else
{ e.Handled = true; }

0
在WPF中,键码值与普通的winforms e.keychar值不同。
在文本框的PreviewKeyDown事件中,添加以下代码:
if ((e.key < 34) | (e.key > 43)) {
if ((e.key < 74) | (e.key > 83)) {
    if ((e.key == 2)) {
        return;
        }
    e.handled = true;
    }
}

这将允许用户仅在数字键盘0-9和D0-D9以及Back键中输入数字。

希望对您有所帮助,谢谢!


无法与Shift键配合使用。您可以插入特殊字符。 - Dragos Stoica

0
private void shomaretextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
  // xaml.cs code
  if (!char.IsDigit(e.Text, e.Text.Length - 1))
    e.Handled = true;
}

在 XAML 中

<TextBox x:Name="shomaretextBox" 
         HorizontalAlignment="Left" 
         Height="28" 
         Margin="125,10,0,0" 
         TextWrapping="Wrap" 
         VerticalAlignment="Top" 
         Width="151" 
         Grid.Column="1"        
         TextCompositionManager.PreviewTextInput="shomaretextBox_PreviewTextInput" />

如果你能添加一些解释、细节,而不仅仅是代码,那就更好了。这样其他用户在未来也能从你的回答中受益,而不仅仅是提问者。只是一个想法 :) - סטנלי גרונן

-1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接