我有一个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)效果很好,但是当我将Text分配给TextBox时,它变为整数(192)。
编辑:a变量正确(55,00)。当将其分配给cell.Text时,它将删除逗号分隔符,并变为:(5500)。var Acell.Text
为什么会这样,我该如何避免呢?
它可能从“ AmountGross”属性获取数据类型,因此,如果它是int,则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