【发布时间】:2020-07-01 13:54:29
【问题描述】:
我可以在文本框 C# 中使用空格分隔符作为千位分隔符吗?
- 示例 1:
将数字 58972,56 写入文本框并显示文本框 58 972,56
- 示例 2:
将数字 2358972,56 写入文本框并显示文本框 2 358 972,56
【问题讨论】:
-
“我可以将空格分隔符设置为千位分隔符吗”当然可以,但是您需要自己实现。开始可能是使用 TextChanged 事件
我可以在文本框 C# 中使用空格分隔符作为千位分隔符吗?
将数字 58972,56 写入文本框并显示文本框 58 972,56
将数字 2358972,56 写入文本框并显示文本框 2 358 972,56
【问题讨论】:
您可以克隆当前文化,更改其NumberFormatInfo.NumberGroupSeparator,最终更改为NumberFormatInfo.CurrencyGroupSeparator,并设置您喜欢的值。
当您Clone() a CultureInfo 对象时,这些属性不再是只读的。
即使原始 CultureInfo 是只读的,克隆也是可写的。 因此,可以修改克隆的属性。
克隆的 CultureInfo 将保留所有默认值,但您更改的值除外。
您现在可以在需要的地方使用修改后的 CultureInfo,而不会影响默认的 Culture 行为。
关于字符串格式,请参阅Standard numeric format strings。
var culture = CultureInfo.CurrentCulture.Clone() as CultureInfo;
culture.NumberFormat.NumberGroupSeparator = " ";
culture.NumberFormat.CurrencyGroupSeparator = " ";
// Elsewhere
[TextBox1].Text = 12345678.89.ToString("N2", culture);
[TextBox2].Text = 12345678.89M.ToString("C", culture);
如果您想更改 CurrentCulture 行为,请将修改后的 CultureInfo 分配给 CultureInfo.CurrentCulture 对象:
CultureInfo.CurrentCulture = culture;
// elsewhere: same behavior, now the default
[TextBox1].Text = 12345678.89.ToString("N2");
您的 TextBox 可以根据所选文化采用双面逻辑。
验证文本后,将使用修改后的文化(如果已定义或默认文化)对其进行格式化:
private void textBox_Validating(object sender, CancelEventArgs e)
{
var numberStyle = NumberStyles.AllowThousands | NumberStyles.AllowDecimalPoint;
if (double.TryParse(textBox.Text, numberStyle, culture ?? CultureInfo.CurrentCulture, out double value)) {
textBox.ForeColor = SystemColors.ControlText;
textBox.Text = value.ToString("N", culture ?? CultureInfo.CurrentCulture);
}
else {
// Notify, change text color, whatever fits
textBox.ForeColor = Color.Red;
}
}
【讨论】:
"yyyy/MM/dd" 不同,用于格式化显示的日期时间)。您可以使用它们来获得精确的格式。 N2 表示有 2 位小数的数字,N 表示使用NumberFormat 和当前文化定义的小数位格式化的数字,如C(货币)。您可以使用这些说明符微调您的格式化输出。
您可以使用Validated 事件来格式化输入:
private void TextBox1_Validated(object sender, EventArgs e)
{
TextBox txt = (TextBox)sender;
if (Decimal.TryParse(txt.Text, out var d)) {
txt.Text = d.ToString("# ### ### ### ### ##0.00");
}
}
它使用当前区域性来确定是否将小数分隔符显示为小数点或逗号。您还可以指定特定的文化:
txt.Text = d.ToString("# ### ### ### ### ##0.00", new CultureInfo("de"));
但在格式字符串本身中总是使用小数点。
在 winforms 中格式化 TextBox 的标准方法是使用 data binding。在绑定属性中,您可以指定格式字符串。
【讨论】: