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;
                        }

                        if (decimal.TryParse(textBox.Text, out var anyAmount))
                        {
                            // Text成功转为deciml后逻辑
                        }
                    }
                    else
                    {
                        textBox.MaxLength = textBox.Text.Length + 2;
                    }
                }
                else
                {
                    // Text为空逻辑
                }
            }
        }

 

你可能感兴趣的:(WPF,WPF,TextBox限制数字,WPF,TextBox两位小数,WPF,TextBox字符长度)