【问题标题】:Currency TextBox accepting numbers only in universal store app货币文本框仅在通用商店应用程序中接受数字
【发布时间】: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


【解决方案1】:

AFAIK 没有专门的课程。但是,下面是一个 MSDN article,它显示了一个由 TextBox 驱动的类,它在过去对我来说很好用。

希望这会有所帮助!

https://msdn.microsoft.com/en-us/library/ms229644(v=vs.100).aspx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-16
    • 2015-06-02
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    相关资源
    最近更新 更多