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