【发布时间】:2015-12-07 05:16:28
【问题描述】:
我正在开发通用 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;
}
}
【问题讨论】:
-
您是否尝试设置文本框控件的 InputScope?
标签: c# xaml windows-store-apps win-universal-app