I have a simple view containing a Textbox and a Label.
<TextBox Text="{Binding MyInt, UpdateSourceTrigger=LostFocus, StringFormat='{}{##.##}'}"/>
<Label Content="{Binding MyStr2}"/>
And in my
ViewModel, I have
private decimal myInt;
public decimal MyInt
{
get { return myInt; }
set
{
if (value == myInt) { return; }
myInt = value;
OnPropertyChange();
OnPropertyChange("MyStr2");
}
}
public string MyStr2
{
get
{
return myInt.ToString("N2", CultureInfo.CreateSpecificCulture("en-IN"));
}
}
Simply speaking, the TextBox Text is bound to a decimal value, and the Label is supposed display the value in the textbox with proper formatting.
Since I have LostFocus as my UpdateSourceTriggerin TextBox, I press TAB in order for the validation and binding to work.
Without the StringFormat attribute in the TextBox, I cannot enter a decimal point in it. Hence, the StringFormat is necessary
So when I enter a decimal value, everything works properly. The Label properly displays the formatted number.
When I enter some garbage non-decimal value, the TextBox Border turns red indicating validation error. But, the very next time I enter some valid data, like 500, in the TextBox, and lose focus, the TextBox becomes blank, with the following error in Output Window:
System.Windows.Data Error: 6 : 'StringFormat' converter failed to convert value '500' (type 'Decimal'); fallback value will be used, if available. BindingExpression:Path=MyInt; DataItem='ViewModel' (HashCode=37975124); target element is 'TextBox' (Name='MyIntTextBox'); target property is 'Text' (type 'String') FormatException:'System.FormatException: Input string was not in a correct format.
at System.Text.StringBuilder.AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args)
at System.String.FormatHelper(IFormatProvider provider, String format, ParamsArray args)
at System.String.Format(IFormatProvider provider, String format, Object[] args)
at System.Windows.Data.BindingExpression.ConvertHelper(IValueConverter converter, Object value, Type targetType, Object parameter, CultureInfo culture)'
However, the Label displays 500.00 properly. I have put breakpoints in the ViewModel to see if the TextBox-bound property myInt is updated properly, and sure enough, it is. This only happens when I try to use StringFormat.
What I have tried:
I have tried to use many variations of the StringFormat, but in vain. In fact, some of the StringFormat values leads to erratic behavior of the cursor. But I am forced to use StringFormat, because, without it, I cannot enter a decimal point.
What exactly am I doing wrong?