我正在使用 WPF/MVVM。我将 textbox.Text 绑定到视图模型中的可为空的双精度值。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\}}"/>
Run Code Online (Sandbox Code Playgroud)
或者只使用转换器。例如:
<Window.Resources>
<helper:DoubleConverter x:Key="DoubleConverter" />
</Window.Resources>
...The code omitted for the brevity
<TextBox Text="{Binding Amount, UpdateSourceTrigger=PropertyChanged,
Converter={StaticResource DoubleConverter}}"/>
Run Code Online (Sandbox Code Playgroud)
和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;
}
}
Run Code Online (Sandbox Code Playgroud)