3
votes

I'm trying to use a DateTime? property as a DependencyProperty so that I can bind it in XAML in a Metro-style app.

However, when the app runs (in debug mode), I get a binding error, and the date does not show up in my control:

Error: Converter failed to convert value of type 'System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' to type 'DateTime>'; BindingExpression: Path='Model.Date' DataItem='MyProject.Common.ViewModel.TransactionViewModel, MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'; target element is 'MyProject.Controls.DatePicker' (Name='null'); target property is 'SelectedValue' (type 'DateTime>').

The dependency property is defined as follows:

public static readonly DependencyProperty SelectedValueProperty =
    DependencyProperty.Register("SelectedValue", 
                                typeof (System.Nullable<System.DateTime>),
                                typeof(DatePicker),
                                PropertyMetadata.Create(default(DateTime?)));

In the XAML page, it is used as:

<local:DatePicker  
   Margin="0,10" 
   SelectedValue="{Binding Model.Date, Mode=TwoWay}" 
   FontSize="21.333"/>

Any ideas on how to fix this and get the date showing in the control and bind both ways?

1

1 Answers

6
votes

The problem is DatePicker expects DateTime type not DateTime? which is a syntactic sugar for Nullable. There is no implicit conversion from DateTime? to DateTime. Write your own IValueConverter. You can step yourself back and ask the question: Do you need DateTime? Can you represent a non-existing date as 00/00/00?

Another option is to convert it before binding e.g.

DateTime dateTime = nullDateTime ?? new DateTime(0, 0, 0, 0, 0, 0);