Pergunta

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}}" />
Foi útil?

Solução

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

There is a nice example here.

Outras dicas

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"
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top