在文本框的开头和结尾添加 $ 符号,并在文本框 WPF C# 中将值格式设置为逗号分隔(千位分隔)值

Add $ sign in starting and end of textbox as well as format value as comma separated(thousand separated) values in textbox WPF C#

我尝试过的: 我能够分别实现这两种情况,但如果在 TextChanged 事件中将代码一起添加,则只有一种情况有效。

1)当用户在文本框代码中键入时,在文本的开头和结尾添加 $sign:

private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            string symbol = "$"; 
            if (TB.Text != "" && !TB.Text.StartsWith("$"))
            {
                var selectionIndex = TB.SelectionStart;
                TB.Text = TB.Text.Insert(selectionIndex, symbol);
                TB.SelectionStart = selectionIndex + symbol.Length;
            }
        }

2) 将逗号分隔(千位分隔符)值格式化为用户在文本框代码中键入的值:

 private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            var TB = sender as TextBox;
            string textValue = TB.Text.Replace(",", "");
            if (double.TryParse(textValue, out result))
            {
                TB.TextChanged -= TextBox_TextChanged;
                TB.Text = string.Format("{0:#,#}", result);
                TB.SelectionStart = TB.Text.Length;
                TB.TextChanged += TextBox_TextChanged;
            }
      }

期望的输出 - $3,333.55$ 小数点动态获取 2、3、4 位小数 比如 $4,566.444$, $3,3,456.33$ 等等

这是一个简单的字符串处理任务:

private int DecimalPlaces { get; set; } = 3;
private char Delimiter { get; set; } = '$';

private void TextBox_TextInput(object sender, EventArgs e)
{
  var textBox = sender as TextBox;
  var plainInput = textBox.Text.Trim(this.Delimiter);  
  if (plainInput.EndsWith(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator))
  {
    return;
  }

  if (double.TryParse(plainInput, NumberStyles.Number, CultureInfo.CurrentCulture, out double number))
  {
    var decimalPlacesFormatSpecifier = GetNumberFormatSpecifier(this.DecimalPlaces);
    textBox.Text = $"{this.Delimiter}{number.ToString(decimalPlacesFormatSpecifier, CultureInfo.CurrentCulture)}{this.Delimiter}";
  }
}

private string GetNumberFormatSpecifier(int decimalPlaces)
{
  var specifierBuilder = new StringBuilder("#,#");
  if (decimalPlaces < 1)
  {
    return specifierBuilder.ToString();
  }

  specifierBuilder.Append(".");
  for (int count = 0; count < decimalPlaces; count++)
  {
    specifierBuilder.Append("#");
  }
  return specifierBuilder.ToString();
}

要使上述解决方案稳健,您必须验证输入:

  • 确保用户只能输入数字和
  • 确保不能将插入符号移动到前导“$”之前和尾随“$”之后。为此,您必须跟踪插入符号的位置。