WPF数据网格文本列无法输入浮点数据中的小数点。

4
我有一个 WPF DataGrid,并使用 DataGridTextColumn 绑定到一个集合。该集合中的项具有一些浮点属性。
当我的程序启动时,我在 DataGrid 中修改浮点属性的值,如果我输入整数值,则可以正常工作。但是,如果我要输入浮点值中的字符“.”时,无法输入。我必须先输入所有数字,然后跳转到“.”位置输入点以完成输入。
所以,在这种情况下,我该如何输入“.”呢?
谢谢。

1
如果您发布了代码,您可能有一个将值转换为整数而不是浮点数的转换器或验证器。 - makc
2
或者这可能是本地化的问题。有些国家使用“.”(句点)作为小数分隔符,而有些国家使用“,”(逗号)作为分隔符。尝试两种方式? - AkselK
4个回答

3

我也遇到了同样的问题。

在我的情况下,这是由于数据绑定选项引起的。

我将 *.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; 更改为 *.UpdateSourceTrigger = UpdateSourceTrigger.LostFocus;

然后就可以直接输入 float 数字了。


0

我想这是因为你的数据网格列绑定到了一个带有十进制数据类型的类成员,例如:

public class Product : ModelBase
{
    decimal _price = 0;
    public decimal Price
    {
        get { return _price; }
        set { _price = value; OnPropertyChanged("Price"); }
    }
}

并且UpdateSourceTrigger=PropertyChanged。摆脱它的一种方法是将属性更改为字符串类型,并像下面这样操作字符串:

string _price = "0.00";
    public string Price
    {
        get { return _price; }
        set 
        {
            string s = value;
            decimal d = 0;
            if (decimal.TryParse(value, out d))
                _price = s;
            else
                _price = s.Substring(0, s.Length == 0 ? 0 : s.Length - 1);
            OnPropertyChanged("Price"); 
        }
    }

希望能有所帮助


0
可能是本地化方面的问题。 尝试更改线程的区域设置,以查看是否可能是问题的原因:
using System.Globalization;
using System.Threading;

Thread.CurrentThread.CurrentUICulture = new CultureInfo("en");

如果您不确定正在运行哪个文化环境,可以通过转到控制面板>时钟、语言和区域或运行以下代码来进行双重检查:

using System.Diagnostics;

Debug.WriteLine("decimal: " + Thread.CurrentThread.CurrentUICulture.NumberFormat.NumberDecimalSeparator);
Debug.WriteLine("thousand: " + Thread.CurrentThread.CurrentUICulture.NumberFormat.NumberGroupSeparator);

嗨,感谢您回答我的问题。在检查了我的本地化设置后,我的电脑设置为:“小数符号:.” 这个设置是正确的。 - Alvin

0

尝试在绑定中使用这个正则表达式验证。

<Validator:RegexValidationRule x:Key="DecimalValidatorFor3Digits"
    RegularExpression="^\d{0,3}(\.\d{0,2})?$"
    ErrorMessage="The field must contain only numbers with max 3 integers and 2 decimals" />

谢谢

Ck Nitin(TinTin)


你好,感谢回答我的问题。我能否在绑定中使用StringFormat来解决我的问题?在DataGridTextColumn.Binding中只有ValidatesOnDataErrors、ValidatesOnExceptions、ValidatesOnNotifyDataErrors和StringFormat可用。 - Alvin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接