自定义控件之NumberTextBox

    /// <summary>
    /// 允许输入数字的TextBox,禁止粘贴,允许backspace、left、right、enter键
    /// </summary>
    public class NumberTextBox : TextBox
    {
        public NumberTextBox()
        {
            DataObject.AddPastingHandler(this, Text_Pasting);
        }

        protected override void OnPreviewKeyDown(KeyEventArgs e)
        {
            if ((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9 && e.KeyboardDevice.Modifiers != ModifierKeys.Shift)
                || (e.Key >= Key.D0 && e.Key <= Key.D9 && e.KeyboardDevice.Modifiers != ModifierKeys.Shift) ||
                e.Key == Key.Back || e.Key == Key.Left || e.Key == Key.Right || e.Key == Key.Enter)
            {
                if (e.KeyboardDevice.Modifiers != ModifierKeys.None)
                {
                    e.Handled = false;
                }
            }
            else
            {
                e.Handled = true;
            }
        }

        private void Text_Pasting(object sender, DataObjectPastingEventArgs e)
        {
            //禁止Pasting
            e.CancelCommand();
        }
    }

  上述代码屏蔽了小数点输入。

原文地址:https://www.cnblogs.com/saybookcat/p/5191953.html