Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set value to null in WPF binding

please take a look at the following line

<TextBox Text="{Binding Price}"/>

This Price property from above is a Decimal? (Nullable decimal).

I want that if user deletes the content of the textbox (i.e. enters empty string, it should automatcally update source with null (Nothing in VB).

Any ideas on how I can do it 'Xamly'?

like image 244
Shimmy Weitzhandler Avatar asked Oct 17 '22 07:10

Shimmy Weitzhandler


2 Answers

I am using .NET 3.5 SP1 so it's very simple:

<TextBox Text="{Binding Price, TargetNullValue=''}"/>

Which stands for (thanks Gregor for your comment):

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

sys is the imported xml namespace for System in mscorlib:

xmlns:sys="clr-namespace:System;assembly=mscorlib"

Hope that helped.

like image 237
Shimmy Weitzhandler Avatar answered Oct 19 '22 20:10

Shimmy Weitzhandler


This value converter should do the trick :

public class StringToNullableDecimalConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, 
        CultureInfo culture)
    {
        decimal? d = (decimal?)value;
        if (d.HasValue)
            return d.Value.ToString(culture);
        else
            return String.Empty;
    }

    public object ConvertBack(object value, Type targetType, 
        object parameter, CultureInfo culture)
    {
        string s = (string)value;
        if (String.IsNullOrEmpty(s))
            return null;
        else
            return (decimal?)decimal.Parse(s, culture);
    }
}

Declare an instance of this converter in the ressources :

<Window.Resources>
    <local:StringToNullableDecimalConverter x:Key="nullDecimalConv"/>
</Window.Resources>

And use it in your binding :

<TextBox Text="{Binding Price, Converter={StaticResource nullDecimalConv}}"/>

Note that TargetNullValue is not appropriate here : it is used to define which value should be used when the source of the binding is null. Here Price is not the source, it's a property of the source...

like image 12
Thomas Levesque Avatar answered Oct 19 '22 19:10

Thomas Levesque