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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With