WPF Date String Format in XAML [duplicate]

2019-04-30 05:32发布

问题:

This question already has an answer here:

  • WPF Binding StringFormat Short Date String 6 answers

I am trying to format string after a date has been selected by the DatePicker. The Format that I am getting is "9/5/2013 12:00:00 AM" and what I am trying to get is "9/5/2013". Can someone tell me what I am doing wrong with the string format?

<DataGridTemplateColumn Header="Start">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Start, StringFormat=d}" FontFamily="Verdana" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
    <DataGridTemplateColumn.CellEditingTemplate>
        <DataTemplate>
            <DatePicker SelectedDate="{Binding Start}" FontFamily="Verdana"  >
                <DatePicker.CalendarStyle>
                    <Style TargetType="Calendar">
                          <Setter Property="DisplayMode" Value="Month"/>
                    </Style>
                </DatePicker.CalendarStyle>
            </DatePicker>
        </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>

回答1:

Try the following:

<TextBlock Text="{Binding Start, StringFormat=d}" />

This requires .NET 3.5 SP1 or above.

Btw.: StringFormat is case sensitive. "d" is the short date format specifier while "D" is the long date format specifier.