我正在开发一个通用的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;
}
}
发布于 2015-12-07 07:04:55
AFAIK目前还没有专门的类来解决这个问题。然而,下面是一个MSDN article,它显示了一个由TextBox驱动的类,它在过去对我来说工作得很好。
希望这能有所帮助!
https://msdn.microsoft.com/en-us/library/ms229644(v=vs.100).aspx
https://stackoverflow.com/questions/34126918
复制相似问题