c# - 以 double 存储十进制数?使用 updatesourcetrigger 作为 PropertyChanged 的​​属性

标签 c# wpf xaml

我正在使用 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/

相关文章:

c# - 将数据网格绑定(bind)到另一个数据网格的选定项

wpf - CommandManager.RequerySuggested 如何工作?

.net - 如何在WPF中实现嵌入阴影效果

wpf - 为什么有些属性需要在样式中定义一个默认值,DataTrigger 才会生效?

c# - 为什么在 WebAPI 自定义操作过滤器中获取 Request.UserHostAddress 时总是获取相同的 IP?

c# - 在 XML 文档中使用 C# 从不同分支的父节点检索叶子

c# regex 高cpu使用率

c# - Unity2D/C# : How do I make a raycast ignore its first collision?

c# - 使用文本框过滤 WPF 数据网格

c# - 使用 MVVM 以编程方式创建 XAML Canvas