WPF TextBox 只能输入数字,并限制输入大小

       
        /// <summary>
        /// 文本框文本输入事件
        /// </summary>
        private void txt_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            Regex regex = new Regex("^[0-9]+$");
            e.Handled = !regex.IsMatch(e.Text);

            if (e.Handled)
                return;

            try
            {
                TextBox txtBox = sender as TextBox;

                string strTag = txtBox.Tag.ToString().Replace("Seconds", "").Replace("ms", "").Replace("s", "").Replace("d", "").Replace("%", "")
                    .Replace("(", "").Replace(")", "").Replace("(", "").Replace(")", "");
                string strText = txtBox.Text + e.Text;

                int max = 0;
                int min = 0;

                if (!string.IsNullOrWhiteSpace(strTag))
                {
                    string[] strs = strTag.Split('-');
                    max = min = int.Parse(strs[0]);
                    foreach (string str in strs)
                    {
                        int num = int.Parse(str);
                        if (num < min)
                            min = num;
                        if (num > max)
                            max = num;
                    }
                }

                int number = int.Parse(strText);
                if (number >= min && number <= max)
                    e.Handled = false;
                else
                    e.Handled = true;
            }
            catch (Exception ex)
            {
                e.Handled = true;
            }
        }

        /// <summary>
        /// 键盘按键事件
        /// 禁用粘贴
        /// </summary>
        private void txt_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if ((e.KeyStates == Keyboard.GetKeyStates(Key.LeftCtrl) || e.KeyStates == Keyboard.GetKeyStates(Key.RightCtrl)) && e.KeyStates == Keyboard.GetKeyStates(Key.V))
                e.Handled = true;
            else
                e.Handled = false;
        }

                                <TextBox Name="txt" Text="3" Tag=" s ( 0 - 20 s )" IsEnabled="False" HorizontalAlignment="Left" VerticalAlignment="Top" Width="120" Height="25" Margin="5,20,0,0" Style="{DynamicResource txtBoxStyle}"
                                         input:InputMethod.IsInputMethodEnabled="False" PreviewTextInput="txt_PreviewTextInput" PreviewKeyDown="txt_PreviewKeyDown"/>


  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值