Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF DatePicker, display todays date with binding to property

Tags:

This is a possible duplicate of Set the Default Date of WPF Date Picker to Current Date but I have tried the code from the question and it doesn't work, hopefully I am missing something simple

OK as the question states, I want to display the current date when the view loads, however, I have the SelectedDate property bounded to a property of mine, and I dont think you can use "Text" because the property that I am binding to is a DateTime property. yes, I could do a convert in the model but XAML (I think) should be able to do this for me.

OK I know what is the problem, the date is coming out "01/01/0001" because of course, its binding to my property which is defaulted to 01/01/0001, so I guess I will need to do some C# code in my property to say if its 01/01/0001, use DateTime.Now and if not, use the property.

The XAML

    <DatePicker HorizontalAlignment="Left" 
                DisplayDate="{x:Static System:DateTime.Now}"
                SelectedDate="{Binding AvailableFrom, Mode=TwoWay}"
                Margin="139,58,0,0" 
                VerticalAlignment="Top" 
                Width="120"/> 

Am happy to delete this after if the big reps think it is a duplicate,

What I did to resolve...

     get
     {

         if (m_AvailableFrom == DateTime.MinValue)
             return DateTime.Now;

        return m_AvailableFrom;
     }

Cheers for the help

like image 326
user3428422 Avatar asked May 02 '14 14:05

user3428422


2 Answers

I personally would just assign DateTime.Now to the AvailableFrom property in the ViewModel code.

If you want to use XAML though, one option is to make the AvailableFrom property a DateTime? (nullable DateTime) rather than a DateTime. Then the default value is null rather than "01/01/0001".

Then, in your XAML you can use

xmlns:System="clr-namespace:System;assembly=mscorlib"

<DatePicker
    HorizontalAlignment="Left"
    SelectedDate="{Binding
        Path=AvailableFrom,
        Mode=TwoWay,
        TargetNullValue={x:Static System:DateTime.Now}}"
    Margin="139,58,0,0" 
    VerticalAlignment="Top" 
    Width="120" />

and the UI will display the current date anytime that AvailableFrom is null.

like image 67
Josh Graham Avatar answered Sep 21 '22 06:09

Josh Graham


The MSDN link for the SelectedDate property below shows it as nullable. I think instead of returning DateTime.Now just return null if it isn't set and I suspect like other controls with nullable fields, it will simply display nothing.

DatePicker.SelectedDate MSDN Link

like image 20
steviesama Avatar answered Sep 20 '22 06:09

steviesama