Darf Zon
Darf Zon

Reputation: 6378

Validating a nullable int using a IValueConverter

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:

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}}" />

Upvotes: 2

Views: 2971

Answers (2)

Rohit Vats
Rohit Vats

Reputation: 81243

Why do you need a converter for this, WPF binding is powerful enough to handle this case.

  • First of all if you bind the textBox with int? value and you try to set the string to it (2b), it will automatically show red validation error border around it.

  • Second if you want to set the null value in case of Empty string, all you need to set the TargetNullValue for your binding.

This code sample will work for you -

<TextBox Text="{Binding Number, TargetNullValue={x:Static s:String.Empty},
                 UpdateSourceTrigger=PropertyChanged}"/>

Make sure you add the namespace system namespace to your xaml -

xmlns:s="clr-namespace:System;assembly=mscorlib"

Upvotes: 2

m0sa
m0sa

Reputation: 10940

Implement the IDataErrorInfo interface in your view model class instead of using the NullableIntValidation class.

There is a nice example here.

Upvotes: 2

Related Questions