限制文本框仅允许十进制数

时间:2013-12-03 12:45:20

标签: c# .net wpf validation textbox

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

  1. 仅允许数字0-9(允许上方小键盘0-9和右小键盘 键0-9);
  2. 只允许一个点在启动时不出现。
  3. 有效:

      
        
    • 0.5
    •   
    • 1
    •   
    • 1.5000
    •   

    无效:

      
        
    • 0.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;
        }
    }
    

2 个答案:

答案 0 :(得分:2)

如果您还想允许复制和粘贴,则无法使用键盘事件进行复制和粘贴。 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;
}

答案 1 :(得分:-1)

您只需在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;