1

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:

<TextBox Text="{Binding Txt, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

and the property:

  double txt;
    public double Txt
    {
        get { return txt; }
        set { txt = value; OnPropertyChanged("Txt"); }
    }

it seems when i try to enter -0.54 it changes immediatly to 0, why?

David Michaeli
  • 367
  • 5
  • 26
  • 3
    Do you need your view model to be updated every time text changes as you do now with `UpdateSourceTrigger=PropertyChanged` or can you remove that and update view model by default on lost focus? Every time you press a key WPF needs to convert `string` to `double` when posting value to view model and when you type in _-0_ it will parse to _0_ – dkozl Jun 15 '14 at 13:59
  • You could go with text and ValidatesOnDataErrors but it is a bit of work. Or you could go with a UpdateSourceTrigger=Explicit and not update if starts with a - until you get a number other than 0. – paparazzo Jun 15 '14 at 17:29
  • BTW. -045 is not less than -1 ;). – Maciej Nowicki Sep 23 '15 at 07:30

2 Answers2

5

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

Avneesh
  • 654
  • 4
  • 6
1

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");
            }
        }
    }
Avneesh
  • 654
  • 4
  • 6