[英]C# WPF - Format number with commas while typing in text box
假设存在此文本框,并且当用户键入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() == '.');
}
除了预览textinput处理程序之外,您还需要将文本框与stringformat绑定到int / long变量
<TextBox DockPanel.Dock="Top" Text="{Binding Value, UpdateSourceTrigger=PropertyChanged, StringFormat={}{0:#,0}}"
PreviewTextInput="TextBox_PreviewTextInput"
/>
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 == ',');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.