tags:

views:

117

answers:

1

I have a textbox that binds to an integer property.

What can I do so that when there is nothing no valid text in the textbox that the property gets set to 0.

Really I think this can be extended so that if the binding fails then we set the source to default(T).

I need a nudge in the right direction.

TargetNullValue is the opposite of what I'm looking for(I think), that sets the textbox text when the source is null. I want when the textbox text is an invalid binding value to set the source as it's default.

+2  A: 

Applying a converter such as the following to your binding should do the trick

public class TextConverter : IValueConverter
{
    public object Convert(object value, Type targetType,
        object parameter, CultureInfo culture)
    {
        int actual = (int)value;

        return actual.ToString();
    }

    public object ConvertBack(object value, Type targetType,
        object parameter, CultureInfo culture)
    {
        string actual = (string)value;

        int theValue = 0;
        int.TryParse(actual, out theValue);

        return theValue;
    }
}

Your textbox binding would look something like this

<TextBox Text="{Binding ... Converter={StaticResource convert}}"></TextBox>

With the convertor defined as a resource of your Window/Control/...

Simon Fox