货币文本框只接受通用商店应用程序中的数字
本文关键字:应用程序 数字 文本 货币 | 更新日期: 2023-09-27 18:25:58
我正在开发一款通用Windows应用程序。我有一个TextBox
,我只接受数字。并且,将TextBox
格式化为美国货币(没有$符号,只有逗号和小数)
我的TextChanged
中已经有了下面的工作代码。此外,为了便于阅读,请发表评论。我只是想知道,既然我对这件事很陌生,我做得对吗?有没有更好的方法来实现同样的目标?我觉得很奇怪,MS没有为这么简单的事情加入烘焙方式。
感谢
private void textBox_TextChanged(object sender, TextChangedEventArgs e)
{
// Do not apply if textbox is empty - needed to avoid exceptions
if (textBox.Text.Length == 0) { return; }
decimal charInput;
string value = textBox.Text.Replace(",", "").Replace(".", "").TrimStart('0');
// Make sure to only accept numbers as input
if (decimal.TryParse(value, out charInput))
{
charInput /= 100;
//Unsub the event so we don't enter a loop
textBox.TextChanged -= textBox_TextChanged;
//Format numbers as currency
textBox.Text = string.Format(new System.Globalization.CultureInfo("en-US"), "{0:N}", charInput);
textBox.TextChanged += textBox_TextChanged;
textBox.Select(textBox.Text.Length, 0);
}
else {
// Remove last character if NOT a number
textBox.Text = textBox.Text.Remove((textBox.Text.Length - 1));
// force cursor to the end of text to avoid random movements
textBox.SelectionStart = textBox.Text.Length;
}
}
AFAIK没有专门的类。然而,下面是MSDN的一篇文章,它展示了一个由TextBox驱动的类,它在过去对我来说很好。
希望这能有所帮助!
https://msdn.microsoft.com/en-us/library/ms229644(v=vs.100).aspx