alratar
alratar

Reputation: 25

DatePicker default date in other format

I have a WPF window with a DatePicket controller. I would like to show the current date not the "Show Calendar" text.

I used this reference

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

and this code

<DatePicker x:Name="DatePicker1" Grid.Column="1" Grid.Row="0" SelectedDate="{x:Reference sys:DateTime.Now}">

It works fine but I would like to change the date format like this: yyyy. mm. dd. How can I do this?

Upvotes: 2

Views: 2618

Answers (2)

haldo
haldo

Reputation: 16711

You can do so by changing the template of the date picker to modify the underlying textbox. Please see example below:

<DatePicker SelectedDate="{x:Static sys:DateTime.Now}">
   <DatePicker.Resources>
      <Style TargetType="DatePickerTextBox">
         <Setter Property="Control.Template">
            <Setter.Value>
               <ControlTemplate>
                  <TextBox x:Name="PART_TextBox"
                     Text="{Binding Path=SelectedDate, StringFormat={}{0:yyyy.MM.dd}, 
                     RelativeSource={RelativeSource AncestorType={x:Type DatePicker}}}" />
               </ControlTemplate>
            </Setter.Value>
         </Setter>
      </Style>
   </DatePicker.Resources>
</DatePicker>

I changed SelectedDate="{x:Static sys:DateTime.Now}" from x:Reference to x:Static to get it working when testing.

Result: enter image description here

BTW, if you want to re-use this code for multiple datepickers then you can just copy the XAML for the <Style></Style> tags (and everything within) and place that into your App.xaml under <Application.Resources> and the style/format will be applied to all of the date pickers.

I found the above code here.

Upvotes: 5

Manoj Choudhari
Manoj Choudhari

Reputation: 5634

You will need to specify the format as shown below, Below is example of text block:

<TextBlock Text="{Binding Source={x:Static system:DateTime.Now}, StringFormat=Date: {0:yyyy.MM.dd}}" />

For DatePicker, you will have to set the control template to modify the TextBlock. Below is the sample code from:

<Style TargetType="{x:Type DatePickerTextBox}">
 <Setter Property="Control.Template">
  <Setter.Value>
   <ControlTemplate>
    <TextBox x:Name="PART_TextBox"
     Text="{Binding Path=SelectedDate, StringFormat='dd MM yyyy', 
     RelativeSource={RelativeSource AncestorType={x:Type DatePicker}}}" />
   </ControlTemplate>
  </Setter.Value>
 </Setter>
</Style>

You can use any standard DateTime format here. Hope this helps.

Upvotes: 0

Related Questions