WPF TextBox 限定输入

步骤一:禁用输入法

  

    

  

步骤二:监测 TextBox 的 PreviewTextInput事件   

        private void TextBox_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
        {   
            //Regex re = new Regex("[^A-F0-9]");  // 只允许输入大写字母A~F和数字0~9

            string str = tbox.Text;
            bool isNumber = System.Text.RegularExpressions.Regex.IsMatch(str, @"^[1-9]\d*$");// 只允许输入大于0的数字
            if (!isNumber)
            {
                tbox.Text = null;
                //tbxPage.Text = "1";
                return;// 不是正整数,清空输入.
            }
        }

你可能感兴趣的:(WPF)