1. 程式人生 > >WPF TextBox 只能輸入數字,並限制輸入大小

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"/>