An issue when TextBox is binding to double and enter negative number that little than -1

后端 未结 2 1124
孤街浪徒
孤街浪徒 2021-01-24 02:07

I have an issue when i binding a textbox to Propery and enter a negative number that is less than -1 - for example -0.45:

the textbox:



        
相关标签:
2条回答
  • 2021-01-24 02:27

    when you enter the decimal value it becomes 0 again so the best way to do this is using the lostfocus trigger:

     <TextBox Text="{Binding Txt, Mode=TwoWay, UpdateSourceTrigger=LostFocus}"  Grid.Row="0"/>
    

    Also you need to do this in the view model:

    public double Txt
        {
            get { return txt; }
            set
            {
                if (!txt.Equals(value))
                {
    
                    txt = value;
                    OnPropertyChanged("Txt");
                }
            }
        }
    
    0 讨论(0)
  • 2021-01-24 02:28

    Here is the convertor that does the job ( So leave your view model as it is- You can use it for both decimal and double). We just need to hold the decimal and -ve position initially:

     public class DecimalConverter:IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value !=null)
            {
                return value.ToString();
            }
            return Binding.DoNothing;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string data = value as string;
            if (data == null)
            {
                return value;
            }
            if (data.Equals(string.Empty))
            {
                return 0;
            }
            if (!string.IsNullOrEmpty(data))
            {
                decimal result;
                //Hold the value if ending with .
                if (data.EndsWith(".") || data.Equals("-0"))
                {
                    return Binding.DoNothing;
                }
                if (decimal.TryParse(data, out result))
                {
                    return result;
                }
            }
            return Binding.DoNothing;
        }
    }
    

    So we hold the values or do nothing on binding

    0 讨论(0)
提交回复
热议问题