DataContext property bound to TextBox.Text doesn't update when the TextBox is cleared

In my SilverLight application I have a TextBox.Text bound to a nullable decimal of the DataContext. When I change the value of the TextBox for example from 25 to 6 it works, the property's setter on the DataContext is executed and the backing field updated, but when I clear the TextBox manually it doesn't work, the setter is not called.

public decimal? Order 
    get { return order; }
    set { order = value; }
decimal? order;

xaml snippet:

    Text="{Binding Path=Order, Mode=TwoWay}"
    IsEnabled="{Binding Path=IsDefaultVisibleEnabled, Mode=TwoWay}"/>


An ordinary TextBox only updates the binding source on LostFocus by default. I don't know what your PraTextBox does. But I recommend you check whether it updates the source on LostFocus or on PropertyChanged.

Try specifying the UpdateSourceTrigger inside the binding:

Text="{Binding Path=Order, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"

Next try: use a converter:

public class NullableDecimalConverter : IValueConverter
    public object Convert(object value, Type targetType, object parameter,
        CultureInfo culture) { return value; }

    public object ConvertBack(object value, Type targetType, object parameter,
        CultureInfo culture)
        string decimalString = value as string;
        decimal parsedDecimal;
        if (decimalString != null && Decimal.TryParse( decimalString,
                                                       out parsedDecimal ))
            return parsedDecimal;
            return null;

the binding:

Text="{Binding Path=Order, Mode=TwoWay,
    Converter={StaticResource myNullableDecimalConverter}}"

Apparently Silverlight (and WPF as long as I know) treat an empty TextBox as an empty string and not null.. Also they believe that empty string conversion to a number is undetermined, so if you bind a number to a textbox, once you set value to the number, you cannot clear it anymore.

PropetyChanged doesnt fire simply because the number hasnt changed - get debugger and see it for yourself.

In Silverlight 5 you can use this:

<TextBox Text="{Binding SOMEFIELD, Mode=TwoWay, TargetNullValue=''}"

where SOMEFIELD is Nullable or other number..

Need Your Help

Allow a button press by true or false variable AS3

actionscript-3 flash if-statement boolean flashdevelop

I have been making an advent calendar in which when you press the button the door opens. I have created a variable to control which date you can open them on called 'AllowOpen' if it is the right d...

Converting uneven rows to columns with FasterCSV

arrays ruby transpose fastercsv

I have a CSV data file with rows that may have lots of columns 500+ and some with a lot less. I need to transpose it so that each row becomes a column in the output file. The problem is that the ...