How do I get a TextBox to only accept numeric input in WPF?

后端 未结 30 2288
悲哀的现实
悲哀的现实 2020-11-22 03:40

I\'m looking to accept digits and the decimal point, but no sign.

I\'ve looked at samples using the NumericUpDown control for Windows Forms, and this sample of a Num

30条回答
  •  清酒与你
    2020-11-22 04:21

    In the WPF application, you can handle this by handling TextChanged event:

    void arsDigitTextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
    {
        Regex regex = new Regex("[^0-9]+");
        bool handle = regex.IsMatch(this.Text);
        if (handle)
        {
            StringBuilder dd = new StringBuilder();
            int i = -1;
            int cursor = -1;
            foreach (char item in this.Text)
            {
                i++;
                if (char.IsDigit(item))
                    dd.Append(item);
                else if(cursor == -1)
                    cursor = i;
            }
            this.Text = dd.ToString();
    
            if (i == -1)
                this.SelectionStart = this.Text.Length;
            else
                this.SelectionStart = cursor;
        }
    }
    

提交回复
热议问题