Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind TextBox to Nullable Double?

Tags:

c#

wpf

I am trying to bind a Double? to a TextBox, and I am having an issue, because when the user empties the textbox a validation happens. I thought my application had a validation in some place I couldn't find, so I created a quick app to test.

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModel() {Value = 3, Value2 = null};
    }
}

public class ViewModel
{
    public double Value { get; set; }
    public double? Value2 { get; set; }
}

The xaml

    <StackPanel Grid.Row="0" Orientation="Horizontal" Margin="5" Height="20px">
        <TextBlock Margin="0,0,5,0">Double:</TextBlock>
        <TextBox Width="50px" Text="{Binding Value}"></TextBox>
    </StackPanel>
    <StackPanel Grid.Row="1" Orientation="Horizontal" Margin="5" Height="20px">
        <TextBlock Margin="0,0,5,0">Double?:</TextBlock>
        <TextBox Width="50px" Text="{Binding Value2}"></TextBox>
    </StackPanel>

When I run the application the TextBox bound to Value2, is empty, but if I type a value and then delete it, when the TextBox loses focus it shows an error. It only goes away when I type a value.

I found this post suggesting to use a string, but he was originally using a double and not double?

How can I make this work? Is the only way using a string?

It seems odd to me that binding to double? wouldn't allow me setting null values.

like image 483
Dzyann Avatar asked Jan 31 '14 13:01

Dzyann


1 Answers

First of all.

not this:

<TextBox Width="50px"

but this:

<TextBox Width="50"

For second: your case should be solved if you do a trick like that:

instead of :

 <TextBox Width="50px" Text="{Binding Value2}"></TextBox>

do :

<TextBox Width="50" Text="{Binding Value2, TargetNullValue=''}"></TextBox>

hope that helps

like image 108
Eugene P. Avatar answered Nov 03 '22 12:11

Eugene P.