WPF TextBox 輸入限制小數點後兩位

private void TextBox_OnPreviewKeyUp(object sender, KeyEventArgs e)
{
    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爲空邏輯
        }
    }
}
相關文章
相關標籤/搜索