lordhusnain
lordhusnain

Reputation: 97

Empty textbox bound with some decimal value

I have a textbox bound to some decimal value. Now, if I type something in it like 100 and clear it completely (empty). I save the data and it saves 1 in decimal value. Similarly if I tried 200 and clear textbox it saves 2. Remember decimal value is not null. Any ideas?

<TextBox 
    Height="23" 
    VerticalAlignment="Center" 
    Text="{Binding Discount,Mode=TwoWay}" 
    MaxLength="50" 
    TabIndex="28" 
    Grid.Row="2" 
    Grid.Column="1" 
    local:FocusExtension.IsFocused=
        "{Binding Path=IsDiscountFocused,Mode=TwoWay}" 
    Margin="5,0,0,0"/>

Upvotes: 0

Views: 3352

Answers (2)

Eric
Eric

Reputation: 245

Since String.Empty cannot be converted into a decimal per default. The last valid value is kept in the property. You should use a converter as below.

Wpf

<Window.Resources>
    <local:ValueConverter x:Key="valueConverter" />
</Window.Resources>

<TextBox Text="{Binding Path=Value, Mode=TwoWay, Converter={StaticResource valueConverter}}" />

Converter:

public class ValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is string && (string)value == "")
        {
            return 0;
        }

        return value;
    }
}

Clr:

public decimal Value
{
    get { return (decimal)GetValue(ValueProperty); }
    set { SetValue(ValueProperty, value); }
}

Upvotes: 4

blindmeis
blindmeis

Reputation: 22445

i assume that your Discount property in your viewmodel looks like:

public decimal Discount {get;set;}

if you use backspace and clear your textbox you get a binding exception because "" can not convertet to decimal. so the last number remains in your property. actually this should happen when using UpdateSourceTrigger=Propertychanged. but nevertheless you can try using decimal?. if this not help you can also add a converter to convert the "" to a value your viewmodel can handle.

EDIT: i did not see you last comment. but in the case you want a 0 for an empty textbox, just use a converter to return 0 when "" is the input.

Upvotes: 0

Related Questions