WPF DataGridTextColumn Can't type point for float data

大憨熊 提交于 2019-12-23 12:28:36

问题


I had a WPF DataGrid and use DataGridTextColumn Binding to a Collection. The items in Collection had some float property.

When my program launched, I modify the value of float property in DataGrid, if I type a integer value, it works well. But if I type char . for a float value, char . can't be typed. I had to type all the numbers first, and then jump to the . position to type char . to finish my input.

So how can I type . in my situation?

Thanks.


回答1:


Also met the same problem.

For my case, it is due to the data binding options.

I changed from *.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; to *.UpdateSourceTrigger = UpdateSourceTrigger.LostFocus;.

Then it can type float number directly.




回答2:


It could be an issue with Localization. Try changing the Culture settings of your thread to check out if this could be the problem:

using System.Globalization;
using System.Threading;

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

you can double-check the settings if you are unsure in which Culture you are running by going to Control Panel > Clock, Language and Region or running the following code:

using System.Diagnostics;

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



回答3:


Try this Regular Expression Validation in Binding.

<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" />

Thanks

Ck Nitin (TinTin)




回答4:


I suppose it's because your datagridcolumn is bound to your class member with decimal datatype, e.g.

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

and the UpdateSourceTrigger=PropertyChanged. One way to do get rid of it is to change the property to string type, and manipulate the string like below:

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"); 
        }
    }

Hope it helps



来源:https://stackoverflow.com/questions/13949778/wpf-datagridtextcolumn-cant-type-point-for-float-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!