Assuming that CarId is an int
and not string
you probably receive a FormatException. If you create an IValueConverter
and add it to the binding you can prevent exception(s).
The problem is when you input a CarId and its a number, WPF can bind it and will be set as value in your VM. But next time, when the value is invalid (means not convertible to int
) will not be set (exception occours in WPF mscorelib.dll), means old value is still there. Property setter will be never called in this case.
Something like this:
public class FallbackConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
int v = 0; // default if no value provided or value is not convertible to int
if (value != null)
{
var result = int.TryParse(value.ToString(), out v);
}
return v;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
string result = string.Empty;
if (value != null)
{
result = value.ToString();
}
return result;
}
}
In XAML (ofcourse replace to your namespace):
xmlns:converter="clr-namespace:Client.ViewModels.Converters"
Then:
<converter:FallbackConverter x:key="FallbackConverter "/>
<TextBox Text="{Binding Path=Car.CarId, Mode=TwoWay, Converter={StaticResource FallbackConverter}}"/>