Clearing a text field does not bind to a null value

I am having difficulty setting an empty text field to zero in a field with zero DB.

Xaml

<y:TextBox Text="{Binding Year1Cost, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True, ValidatesOnDataErrors=True, ValidatesOnExceptions=True, StringFormat=\{0:c\}}" Grid.Row="3" Grid.Column="1" /> 

When I enter any value into it, the binding is fine and the transmitted value is transmitted
When I leave only one null value, the null value is passed. If I delete the value from the TextBox, the passed value will be the original value of the text field and the user interface will not be notified of the change. Grrrrrrrrrrrrrrrr

For a long time I checked the options, not to mention putting the code behind the OnTextChanged of each field with a zero value, I don’t see the effectiveness at the same time.

Thanks in advance:

ps. Didn't look at TargetNullValue

Visual Studio 2008 - SP1 -.Net 3.5

+6
null data-binding wpf textbox
source share
3 answers

Consider using a value converter . You should be able to implement the ConvertBack method to translate blank lines to zeros.

+3
source share

Set the TargetNullValue property of the binding to String.Empty :

 <TextBox Text="{Binding TargetNullValue={x:Static sys:String.Empty}}"/> 

I tried and it works for me.

And if I'm not mistaken (please forgive me if I am), you should set the StringFormat property as follows:

 StringFormat={}{0:C} 

This may even be the reason for the exception you received.

+14
source share

Only the converter works for me: Here is the link

 public class NullableConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return value == null ? string.Empty : String.Format(culture, "{0}", value); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return string.IsNullOrEmpty(String.Format(culture, "{0}", value)) ? null : value; } } 
+3
source share

All Articles