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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With