I've a TextBox bound to an int property with [Required] and [Range(1, 5)]attribute, when app starts TextBox gets 0, if I press Backspace and delete that 0, I get this message in Debug log:
System.Windows.Data Error: 7 : ConvertBack cannot convert value '' (type 'String'). BindingExpression:Path=Order.PartyCode; DataItem='OrderVM' (HashCode=66572856); target element is 'TextBox' (Name=''); target property is 'Text' (type 'String') FormatException:'System.FormatException: Input string was not in a correct format.
at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
at System.String.System.IConvertible.ToInt32(IFormatProvider provider)
at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
at MS.Internal.Data.SystemConvertConverter.ConvertBack(Object o, Type type, Object parameter, CultureInfo culture)
at System.Windows.Data.BindingExpression.ConvertBackHelper(IValueConverter converter, Object value, Type sourceType, Object parameter, CultureInfo culture)'
and validation doesn't work. I get same error if I use Nullable<int> instead of int!
Is it a must to have string properties to work with TextBox or there's way to solve this problem?
You can fix this by using
TargetNullValuein your binding, like so:<TextBox Text="{Binding Test, TargetNullValue=''}"/>This sets
TargetNullValueto an empty string, which tells the binding that an empty string should be converted tonullfor the binding source.If you're using a normal
int, the result is that your property will not get set at all when the text is changed to an empty string. If you're usingint?then your property will be set tonullwhen the text changes to an empty string.