0

I had the datepicker to have its selected date property bound to the dataset as shown in the XAML below:

<DatePicker x:Name="date_picker" Margin="0,0,0.2,0" SelectedDate="{Binding Date, Mode=TwoWay, 
NotifyOnValidationError=true, ValidatesOnExceptions=true, StringFormat=dd-MM-yyyy}" ToolTip="Please
select a date" FirstDayOfWeek="Monday" SelectedDateFormat="Short" DisplayDateStart="2013-01-01" 
DisplayDateEnd="2020-01-01" />

But when the window loads, I wanted the default output to be today's date instead of the default "Select a date", but when I use the code below, i just get the default "select a date". I think it may be because SelectedDate property is used twice. How would i fix this problem?

date_picker.SelectedDate = DateTime.Today; 
Hamoudy
  • 559
  • 2
  • 8
  • 24
  • Possible duplicate of http://stackoverflow.com/questions/3885912/wpf-datepicker-default-to-todays-date – Florian Gl Mar 10 '13 at 16:01
  • no because i have a problem with databinding and i want to try with other datetime variables, i was using datetime.today as an example – Hamoudy Mar 10 '13 at 16:18

1 Answers1

0

Do not manipulate UI elements in procedural code.

If the DatePicker's SelectedDate property is bound to someobject's Date Property, why don't you just set the data in the underlying object?

public class SomeObject
{
    public DateTime Date {get;set;}

    public SomeObject()
    {
        Date = DateTime.Today;
    }

}

setting UI element's properties in procedural code completely defeats the purpose of DataBinding.

You must keep in mind that UI is Not Data.

Community
  • 1
  • 1
Federico Berasategui
  • 43,562
  • 11
  • 100
  • 154
  • im not sure how to use/reference this SomeObject class – Hamoudy Mar 10 '13 at 16:27
  • @Hamoudy HighCore has used SomeObject because you have not specified what you will be doing with this date variable. For example if your application was an appointment scheduling app and you wanted the datepicker was used for the appointment date, then SomeObject would be a class that describes an Appointment, and might also contain properties for a Name, description etc. The link that HighCore provided shows a good simple example of MVVM. However, you will also need to implement INotifyPropertyChanged if you want to update the UI. I shall post another comment with a link to a nice example – failedprogramming Mar 11 '13 at 02:59
  • https://rachel53461.wordpress.com/2011/05/08/simplemvvmexample/ This helped me heaps when I started MVVM. – failedprogramming Mar 11 '13 at 02:59