1. 程式人生 > 實用技巧 >WPF TextBox正則匹配限制輸入

WPF TextBox正則匹配限制輸入

只能輸入數字和並保留兩位小數點

 private void txt_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            Regex re = new Regex("[^0-9.-]+");
            e.Handled = re.IsMatch(e.Text);

            var textBox = e.OriginalSource as TextBox;
            if (textBox != null)
            {
                if (!string.IsNullOrWhiteSpace(textBox.Text))
                {
                    if (textBox.Text.Substring(textBox.Text.Length - 1) != ".")
                    {
                        if (!textBox.Text.Contains("."))
                        {
                            textBox.MaxLength = 10;//長度為10
                        }

                        if (decimal.TryParse(textBox.Text, out var anyAmount))
                        {
                            // Text成功轉為deciml後邏輯
                        }
                    }
                    else
                    {
                        textBox.MaxLength = textBox.Text.Length + 2;
                    }
                }
                else
                {
                    // Text為空邏輯
                }
            }
        }

只能輸入英文

 private void txt_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            Regex re = new Regex("^[A−Za−z]+");
            e.Handled = re.IsMatch(e.Text);
            Regex reNUmber = new Regex("[^0-9]+");
            e.Handled = !reNUmber.IsMatch(e.Text);
            
        }

只能輸入英文和數字

 private void txr_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            Regex re = new Regex("^[A−Za−z0−9]+");

            if (!e.Text.Equals("0"))
            {
                e.Handled = re.IsMatch(e.Text);
            }
        }

禁用鍵盤貼上

 private void txt_StartNumber_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;
            }
        }