Search code examples
.netwpf.net-coredata-binding

How do i set todays date in datepicker with usage of data-binding?


Currently i'm using a datepicker:

<DatePicker Name="dpEmailConfirmed1" Grid.Row="1" Grid.Column="3" SelectedDate="{Binding EmailConfirmation}" Margin="5"/>

Now i would like to set the datepicker as default to todays date.

All articles i read so far, are using "SelectedDate" for the setting. But in my case i'm using it with a binding to a model, to get the chosen date.

Can i do another way?

I trid already

<my:DatePicker DisplayDate="{x:Static sys:DateTime.Now}"/>

and

dpEmailSent1.Text = DateTime.Now.Date.ToString();

and

dpEmailSent1.DisplayDate = DateTime.Now.Date.ToString();

Solution

  • The binding of the SelectedDate property is correct. Instead of setting the default value in XAML, assign it to the bound EmailConfirmation property in your view model, e.g. in its constructor:

    public class MyEmailViewModel : INotifyPropertyChanged
    {
       public MyEmailViewModel()
       {
          EmailConfirmation = DateTime.Today;
       }
    
       private DateTime _emailConfirmation;
       public DateTime EmailConfirmation
       {
          get => _emailConfirmation;
          set
          {
             if (_emailConfirmation.Equals(value))
                return;
    
             _emailConfirmation = value;
             OnPropertyChanged();
          }
       }
    
       public event PropertyChangedEventHandler PropertyChanged;
    
       protected virtual void OnPropertyChanged(string propertyName = null)
       {
          PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
       }
    
       // ...other view model code.
    }
    

    Since you want to apply the date of today, you can use DateTime.Today instead of DateTime.Now to reset the time component of the instance.

    Also do not forget to implement INotifyPropertyChanged e.g. like in the example above, otherwise changes to the property will not be reflected in the user interface.