Q:

C#/WPF Textbox error : "Value '' cannot be converted", TargetNull not working

I have a Listview and a Textboxbinded to the selected item.
When the user deletes the value in the textbox (which is a double), I get the following error :  Value '' cannot be converted. So I had TargetNullValue='', like this :
<TextBox x:Name="textBoxVoltage" Text="{Binding Voltage, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, TargetNullValue=''}" />

But I still get the error....What am I doing wrong ? Thanks.

A:

The issue is that your Voltage is of the type double and '' cannot be converted to double.
You can change the Voltage type to double? which will allow you to do this.

The alternative is using a converter, but then assuming 0 and empty are the same thing:
public class EmptyDoubleConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null || (double)value == default(double))
            return "";

        return value.ToString();
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (String.IsNullOrEmpty(value as string))
            return default(double);

        return double.Parse(value.ToString());
    }
}

