HariPrasad kasavajjala
HariPrasad kasavajjala

Reputation: 340

Binding Date to DatePicker is not working in UWP

I have a DateTime datatype variable,which is binded to a datepicker.

DatePicker XAML:

<CalendarDatePicker Name="dpDate" VerticalAlignment="Center" 
         Date="{Binding dpDateTime, ElementName=this, Mode=TwoWay}"
         DateChanged="dp_DateChanged">
</CalendarDatePicker>

Code behind, which sets the value:

dpDatetime = DateTime.Now;

But datepicker is not selecting the current date it is selecting the date as 1/1/1917

Upvotes: 0

Views: 3884

Answers (1)

Martin Zikmund
Martin Zikmund

Reputation: 39102

The problem is that the date you are setting is of type DateTime while the calendar expects a DateTimeOffset.

You can fix this quite easily by changing the type of your dpDateTime property to DateTimeOffset.

Overall it is better to use DateTimeOffset instead of DateTime everywhere because it includes timezone information which makes your code more reliable when the user's timezone changes.

Update - INotifyPropertyChanged

Also you have to implement INotifyPropertyChanged so that the value changes are notified to the data-binding. First you have to add implement the INotifyPropertyChanged interface in your class:

public class Page : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    // This method is called by the Set accessor of each property.
    // The CallerMemberName attribute that is applied to the optional propertyName
    // parameter causes the property name of the caller to be substituted as an argument.
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    ...
}

And you then update the property setter to utilize the setter:

private DateTimeOffset _dpDateTime = DateTime.Now;

public DateTimeOffset dpDateTime
{
   get { return _dpDateTime; }
   set 
   {  
       _dpDateTime = value;
       NotifyPropertyChanged();
   }
}

Data binding functionality requires the target properties raise the PropertyChanged event, because data-binding behind the scenes observes this event.

Upvotes: 6

Related Questions