Reputation: 11091
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 its default.
Upvotes: 2
Views: 1183
Reputation: 10591
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/...
Upvotes: 4