Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF datepicker validation error appears when binding value is null

I have a WPF application where I am using a date picker that is bound to an entity framework(with SQL server) entity's date field. I bind it as follows:

<DatePicker x:Name="dtComplete" Style="{StaticResource FTC_DatePicker}" Grid.Column="2" Grid.Row="7" Grid.ColumnSpan="3"                                            
Text="{Binding dtComplete, Mode=TwoWay, ValidatesOnDataErrors=True}"/>

The binding works fine and can be updated to the entity.

My problem is that when the underlying database field is null, I get the select a date watermark, which I want, but that watermark is being validated and coming back as not being of a date format. I want to keep the watermark, but not have the validation trigger until the user changes the input. Also, I want to keep ValidatesOnDataErrors=True because I use that somewhere else to evaluate business logic.

To see what I mean, here is a form that uses the datepicker with a null value for the date, you can see the validation error: wpf datepicker validation error

The output window when debugging gives the following validation conversion error:

System.Windows.Data Error: 7 : ConvertBack cannot convert value '' (type 'String'). BindingExpression:Path=dtComplete; DataItem='job_BF0D6052EEADCDA3C2B6D1A174D77C322D5AB16A035F214705610767131A80F0' (HashCode=17930557); target element is 'DatePicker' (Name='dtComplete'); target property is 'Text' (type 'String') FormatException:'System.FormatException: String was not recognized as a valid DateTime. at System.DateTime.Parse(String s, IFormatProvider provider) at System.Convert.ToDateTime(String value, IFormatProvider provider) at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider) at System.Windows.Data.BindingExpression.ConvertBackHelper(IValueConverter converter, Object value, Type sourceType, Object parameter, CultureInfo culture)'

Can someone help me get rid of this validation error until the user changes the input?

Thanks in advance

like image 561
J King Avatar asked Feb 18 '23 06:02

J King


1 Answers

Figured it out:

I was binding to the text value of hte datePicker, so it was trying to validate the watermark text as a date, but what I really should have been doing was binding to the selectedDate Property as follows:

<DatePicker x:Name="dtComplete" Style="{StaticResource FTC_DatePicker}" Grid.Column="2" Grid.Row="7" Grid.ColumnSpan="3"                                                                                        
 SelectedDate="{Binding dtComplete, Mode=TwoWay, ValidatesOnDataErrors=True}" />

This now behaves as I want, the select a date watermark is still there and the binding date value works. Its all too obvious now. Simple fix

like image 123
J King Avatar answered Feb 19 '23 20:02

J King