0

我正在制作一个敦促输入金额的文本框。因此,当用户在该 TextBox 中键入 1000 时,它会在 TextBox 中自动变为 1,000。这可能吗?

4

3 回答 3

2

我不喜欢基于长度的解决方案(您需要为更大的数字实现更多代码)。

在 google 上找到的一种解决方案是:

在 XAML 文件上:

<code>
<textbox x:name="PurchasePriceTextBox" text="$0.00" keydown="CurrencyTextBox_KeyDown" lostfocus="CurrencyTextBox_LostFocus" />
</code>

在 CS 文件上:

private void CurrencyTextBox_KeyDown(object sender, KeyRoutedEventArgs e)
{
char key = Convert.ToChar(e.Key);
//if the key is not 0-9 prevent the event from being handled further
if (!(key >= '0' && key <= '9'))
   e.Handled = true;  
}
private void CurrencyTextBox_LostFocus(object sender, RoutedEventArgs e)
{
   var textBox = (TextBox)sender;
   decimal value = 0;
   //if the textbox is not already formatted as currency, format it
   if(Decimal.TryParse(textBox.Text.Trim(), NumberStyles.Number | NumberStyles.AllowCurrencySymbol, CultureInfo.CurrentUICulture, out value))
   {
      textBox.Text = string.Format("{0:C}", value);
   }
}

资源

于 2012-10-16T07:20:20.723 回答
0

利用文本框的 textbox_TextChanged 事件,如下所示:

private void textbox_TextChanged(object sender, TextChangedEventArgs e)
    {
        if (textbox.Text.Length ==4)
        {
            textbox.Text = textbox.Text.Insert(1, ",");
            return;
        }        
    }
于 2012-10-16T07:07:38.573 回答
0

在 Focus Leave 事件中,只需根据您的长度循环:

if (textbox.Text.Length <4)
{
    return;
}
int i = 2;
if textbox.Text.Length%2 ==0)
{
    i = 1;
}
l = textbox.Text.Length;
while(l > 3)
{
    textbox.Text = textbox.Text.Insert(i, ",");
    i+=2;
    l-=2;
}
return;
于 2012-10-16T07:28:31.287 回答