无法将 TextBox 文本更改为包含两位小数

Cannot change TextBox Text to contain two decimal places

我有一个 TextBox,在 LostFocus 上我 运行 一个将值转换为末尾有两个零的小数的函数。 (例如,192 变为 192,00)。

xaml中的文本框:

<TextBox x:Name="AmountGross"  
         Text="{Binding AmountGross, StringFormat='0.00',
         UpdateSourceTrigger=PropertyChanged,
         ValidatesOnExceptions=True,
         ValidatesOnDataErrors=true, 
         NotifyOnValidationError=true}" 
         GotKeyboardFocus="TextBoxGotKeyboardFocusHandler"
         TextChanged="TextBoxTextChangedHandler"
         PreviewKeyUp="DEFixedButtonPreviewKeyUpHandler" 
         HorizontalContentAlignment="Right" LostFocus="TextBoxLostFocus" >
 </TextBox>

以及 TextBoxLostFocus 代码:

if (cell.Text != "")
{
    decimal value = -1;
    if (decimal.TryParse(cell.Text, out value))
    {
        string a = string.Format("{0:N}", Convert.ToDecimal(value)); //THIS LINE CONVERTS IT TO 192,00
        cell.Text = a.ToString().Replace(".", ""); //HERE THE CELL.TEXT IS 192
    }
}

转换(192 到 192,00)效果很好,但是当我将文本分配给文本框时,它变为整数 (192)。

编辑: a 变量是正确的 (55,00)。 当它被分配给 cell.Text 时,它会删除逗号分隔符并变为:(5500)。 var A cell.Text

为什么会发生这种情况,我该如何避免?

它可能从 "AmountGross" 属性 中获取数据类型,因此如果它在 TextBox 中获取此类型作为默认数据类型,请尝试将 属性 类型更改为十进制。

我刚刚发现您本地化的小数点分隔符是逗号。

尾随零默认被截断:

(19200,00).ToString() // Output: 19200

您可以使用 the "." custom specifier:

(19200,00).ToString("0.00") // Output: 19200,00

the Numeric ("N") Format Specifier(也将添加组分隔符):

(19200,00).ToString("N2") // Output: 19.200,00