WPF TextBox限制數字輸入並且保留兩位小數和長度限制

  <TextBox  x:Name="txt_SewagePrice" Grid.Row="3" Grid.Column="1"
                                  VerticalContentAlignment="Center"                                          
                                  PreviewTextInput="txt_PreviewTextInput"
                                  input:InputMethod.IsInputMethodEnabled="False"
                                  Margin=" 10,5,10,5"
                                  Height="26"
                                  MaxLength="10"
                                  Style="{StaticResource OuterGlowStyle}"
                                  />
 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爲空邏輯
                }
            }
        }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章