我正在使用 WPF/MVVM。 我将 textbox.Text 绑定(bind)到 View 模型中的可为 null 的 double。 UpdateSourceTrigger = PropertyChanged 而不是 Lostfocus。因此,当在我使用的转换器中使用 Double.Parse(textbox.Text) 输入每个数字时,double 属性将被更新。我在这里使用 PropertyChanged 和转换器,因为我需要做一些其他的验证检查。
我的问题是我需要输入“1.69”。 当我输入“1”时,它会作为“1”添加到属性中。 接下来我输入“.”,但它没有添加为“1”。因为 double.parse 将数字保存为“1”
所以我不能添加小数。请帮忙。提前致谢。
最佳答案
如果您使用 StringFormat=\{0:n\}
,应该没问题。例如:
<TextBox Text="{Binding FooValue, UpdateSourceTrigger=PropertyChanged,
StringFormat=\{0:n\}}"/>
或者只使用转换器。例如:
<Window.Resources>
<helper:DoubleConverter x:Key="DoubleConverter" />
</Window.Resources>
...The code omitted for the brevity
<TextBox Text="{Binding Amount, UpdateSourceTrigger=PropertyChanged,
Converter={StaticResource DoubleConverter}}"/>
和DoubleConverter
:
public class DoubleConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
// return an invalid value in case of the value ends with a point
return value.ToString().EndsWith(".") ? "." : value;
}
}
关于c# - 以 double 存储十进制数?使用 updatesourcetrigger 作为 PropertyChanged 的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36595578/