user3428422
user3428422

Reputation: 4560

WPF DatePicker to show the time as well as the date

I have a DatePicker object in a DataGrid that successfully shows the date from the database or a property:

<DataGridTemplateColumn.CellTemplate>
   <DataTemplate>
      <DatePicker SelectedDate="{Binding Date, StringFormat=dd/MM/yyyy}"/>
   </DataTemplate>   
</DataGridTemplateColumn.CellTemplate>

Now I want to show the time in front of the date. This is what I tried, but it doesn't work:

<DataGridTemplateColumn.CellTemplate>
   <DataTemplate>
      <DatePicker SelectedDate="{Binding Date, StringFormat='dd/MM/yyyy HH:mm:ss'}"/>
   </DataTemplate>   
</DataGridTemplateColumn.CellTemplate>

NOTE: I do not want to do this in the code-behind.

Upvotes: 19

Views: 37937

Answers (3)

Lyra
Lyra

Reputation: 465

You could do something like this:

            <DataGridTemplateColumn Header="YourDate">
                <DataGridTemplateColumn.CellEditingTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <DatePicker SelectedDate="{Binding YourDate, UpdateSourceTrigger=PropertyChanged}" />
                            <TextBox Margin="2 0 0 0" Text="{Binding YourDate, UpdateSourceTrigger=PropertyChanged, StringFormat='t'}" />
                        </StackPanel>
                    </DataTemplate>
                </DataGridTemplateColumn.CellEditingTemplate>
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding YourDate}" />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>

This will show an DatePicker next to an TextBox wich are bound to the same property. The TextBox got an StringFormat to only show the date.

UpdateSourceTrigger is set to PropertyChanged, so the user can't do an conflict.

Upvotes: 2

zaman
zaman

Reputation: 786

Use the extended DateTimePicker

Upvotes: 13

daniele3004
daniele3004

Reputation: 13890

In addition to, without using other components, if you just want to display a date in the format that you want to edit it, you can do this:

    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock  Text="{Binding Path=Date,StringFormat={}{0:dd/MM/yyyy}}"  VerticalAlignment="Center" HorizontalAlignment="Left">
            </TextBlock>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>

Upvotes: 3

Related Questions