C#WPF-在文本框中键入内容时,请使用逗号格式化数字

时间:2018-11-21 16:54:10

标签: c# wpf

假设存在此文本框,并且当用户键入 4000 时,只要键入最后一个零,该文本框应显示 4,000 2030040 ,它应该显示 2,030,040 并实时添加逗号。我想在WPF C#项目中做到这一点。我添加了以下代码,以便用户只能在文本框中键入数字和小数点。 txtAmount 是文本框的名称。

private void txtAmount_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    e.Handled = !char.IsDigit(e.Text.Last()) && !(e.Text.Last() == '.');
}

2 个答案:

答案 0 :(得分:0)

除了预览文本输入处理程序外,您还需要将文本框与stringformat绑定到int / long变量

<TextBox DockPanel.Dock="Top" Text="{Binding Value, UpdateSourceTrigger=PropertyChanged, StringFormat={}{0:#,0}}" 
         PreviewTextInput="TextBox_PreviewTextInput"
         />

答案 1 :(得分:0)

private void UIElement_OnPreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            var textBox = (TextBox)sender;
            var currentText = textBox.Text;

            if (currentText.Length + 1 < 3) return;

            if ((textBox.GetDigitsCount()) % 3 == 0 && currentText.Length != 2)
            {
                textBox.Text = !textBox.HasAnyCommas() 
                    ? currentText.Insert(1, ",") 
                    : textBox.Text.Insert(textBox.Text.Length - 2, ",");
            }

            textBox.SelectionStart = textBox.Text.Length;
        }


public static class Ex
    {
        public static int GetDigitsCount(this TextBox @this) => @this.Text.Count(char.IsDigit);
        public static bool HasAnyCommas(this TextBox @this) => @this.Text.Any(x => x == ',');
    }