【问题标题】:Combination of numeric and price format - TextBox of WPF [duplicate]数字和价格格式的组合-WPF的TextBox [重复]
【发布时间】:2017-08-13 13:33:16
【问题描述】:

我已经使用此代码从用户那里获取价格

<TextBox Name="txtPrice" PreviewTextInput="NumberValidationTextBox" />

我强迫用户只输入数字

private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
{
    Regex regex1 = new Regex("[^0-9]+");
    e.Handled = regex1.IsMatch(e.Text);
}

我如何也提供价格格式,例如:

123,700

【问题讨论】:

  • 如果你将Text绑定到某个视图模型值上,只需将StringFormat设置为TextBox.Text
  • @GeorgeAlexandria 请编写一个适用于字符串格式 000,000,000 和数字格式的示例
  • @AbdullahDibas 我测试了所有这些,都行不通
  • var strFormat = "#,#"; var str = 123456789.ToString(strFormtat, CultureInfo.InvariantCulture);

标签: c# regex wpf textbox


【解决方案1】:

使用可选的千位分隔符测试字符串是否正确格式化为数字:

^\d+(,\d{3})*$

Live demo.

【讨论】:

  • 我尝试像 Regex regex1 = new Regex("^\d+(,\d{3})*$");但是Visual说,“Bad Compile constant value”
  • @alihaghdoust9 尝试添加@:Regex regex1 = new Regex(@"^\d+(,\d{3})*$");
  • 嗯,它现在没有错误,但在这种情况下,我可以写从 A 到 Z 的任何字符
  • 在 Java 中,转义字符需要额外的转义。所以\\d 而不是\d。这对于 c# 可能是一样的。
  • @linden2015 感谢您的帮助,\\ 没有解决
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-16
  • 2013-07-16
  • 1970-01-01
  • 2018-05-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多