【问题标题】:Restrict textbox to allow only decimal numbers [closed]限制文本框只允许十进制数字[关闭]
【发布时间】:2013-12-19 12:51:01
【问题描述】:

我需要制作一个十进制文本框(Money 文本框):

  1. 仅允许数字 0-9(允许上小键盘键 0-9 和右小键盘 键 0-9);
  2. 只允许一个不出现在开头的点。

有效:

  • 0.5
  • 1
  • 1.5000

无效:

  • .5
  • 5.500.55

编辑

我的代码是:

 private void floatTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        e.Handled = !TextBoxValidation.AreAllValidDecimalChars(e.Text);
    }


  public static class TextBoxValidation
{
    public static bool AreAllValidDecimalChars(string str)
    {
        bool ret = false;
        int x = 0;
        foreach (char c in str)
        {
            x = (int)c;
        }
        if (x >= 48 && x <= 57 || x == 46)
        {
            ret = true;
        }
        return ret;
    }
}

【问题讨论】:

  • 好的,所以你有一个要求。请向我们展示你的努力。并解释为什么你的努力失败了。
  • 这里有一个类似的问题,答案是stackoverflow.com/questions/16914224/…
  • @PhoenixReborn,请看我的编辑
  • “向我们解释为什么你的努力失败了”....
  • @Mussammil 您在循环之外进行了验证。这只会检查最后一个字符。此外,如果它是正确的,如果 ANY 字符是 ok 而不是 ALL,它将返回 true。

标签: c# .net wpf validation textbox


【解决方案1】:

如果您还想允许复制和粘贴,则不能使用键盘事件来实现。 TextBox 有一个 TextChanged 事件,它允许您适当地处理此事件。如果你想阻止任何不是数字或点的输入,你可以这样处理:

private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
    //get the textbox that fired the event
    var textBox = sender as TextBox;
    if (textBox == null) return;

    var text = textBox.Text;
    var output = new StringBuilder();
    //use this boolean to determine if the dot already exists
    //in the text so far.
    var dotEncountered = false;
    //loop through all of the text
    for (int i = 0; i < text.Length; i++)
    {
        var c = text[i];
        if (char.IsDigit(c))
        {
            //append any digit.
            output.Append(c);
        }
        else if (!dotEncountered && c == '.') 
        {
            //append the first dot encountered
            output.Append(c);
            dotEncountered = true;
        }
    }
    var newText = output.ToString();
    textBox.Text = newText;
    //set the caret to the end of text
    textBox.CaretIndex = newText.Length;
}

【讨论】:

  • ,感谢您的回复,这不能解决我的要求 2(点永远不会作为第一个字符出现,例如:.5 无效,而 0.5 有效)如何完成此操作
【解决方案2】:

您只需在 TextBox 上实现两个事件处理程序即可实现您的目标:

TextCompositionEventHandler textBox_PreviewTextInput = 
    new TextCompositionEventHandler((s, e) => e.Handled = !e.Text.All(
    c => Char.IsNumber(c) || c == '.'));
KeyEventHandler textBox_PreviewKeyDown = new KeyEventHandler(
    (s, e) => e.Handled = e.Key == Key.Space);

textBox.PreviewTextInput += textBox_PreviewTextInput;
textBox.PreviewKeyDown += textBox_PreviewKeyDown;

【讨论】:

  • 尝试粘贴“Hello World!”进入文本框。
  • +1 感谢@BasBrekelmans 指出这一点......我已经使用它多年了,但从未注意到这一点。我会使用 TextChanged 事件解决这个问题,但不想复制你的答案,我会保留 -1。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-10
  • 2019-04-22
  • 2012-09-05
  • 2013-04-23
  • 1970-01-01
  • 2022-01-05
相关资源
最近更新 更多