I'm trying to perform a validation property. We have a nullable property called:
public int? Number
{
get { return _number; }
set
{
if (_number != value)
{
_number = value;
RaisePropertyChanged("Number");
}
}
}
And this property is bound to a textbox. I only want to validate this two escenarios:
- Imagine that the user left the textbox empty (textbox.text=""), so Number property must receive null value (instead "" ).
- And if the user inputs "2b", Number property must have a null value (because is an error), but the textbox must still say "2b".
So the implementation for this is:
public class IntConverter : IValueConverter
{
private static readonly IntConverter defaultInstance = new IntConverter();
public static IntConverter Default { get { return defaultInstance; } }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is int?)
{
int? intValue = (int?)value;
if (intValue.HasValue)
{
return intValue.Value.ToString();
}
}
return Binding.DoNothing;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is string)
{
int number;
if (Int32.TryParse((string)value, out number))
{
return number;
}
}
return null;
}
}
The code above is really working, but just one thing is not doing good. When the user inputs "2b", at this moment, should show the error (red border). How can I fix it?
NOTE: Validations properties are in true.
<TextBox Text="{Binding Number, UpdateSourceTrigger=PropertyChanged,
ValidatesOnExceptions=True, ValidatesOnDataErrors=True, NotifyOnValidationError=True, TargetNullValue={x:Static sys:String.Empty},
Converter={x:Static c:IntConverter.Default}}" />
Implement the IDataErrorInfo interface in your view model class instead of using the NullableIntValidation class.
There is a nice example here.