问题
Im using the Datepicker control to get a date and display it in a Textblock in WP7. I want it to only show the date and not the time. The Datepicker only shows the date, but when I want to show it in the TextBlock it shows both date and time. I use databinding to set the date in the Datepicker:
public class Task
{
public DateTime Date { get; set; }
public Task()
{
Date = DateTime.Now;
}
}
XAML:
<toolkit:DatePicker Value="{Binding Mode=TwoWay, Path=Date}" FlowDirection="RightToLeft" />
<TextBlock x:Name="TxbTaskDate" Text="{Binding Date}" />
How do I get the TextBlock to only show the date and not time?
回答1:
You should add a StringFormat
<TextBlock x:Name="TxbTaskDate"
Text="{Binding Date, StringFormat='{}{0:dd.MM.yyyy}'}" />
回答2:
Try this:
<TextBlock x:Name="TxbTaskDate" Text="{Binding Date, StringFormat=d}" />
回答3:
A .NET DateTime always includes the Time. Your issue is with formatting in the TextBlock
<!-- untested -->
<TextBlock x:Name="TxbTaskDate" Text="{Binding Date StringFormat={0:dd-MM-yyyy}}" />
回答4:
DateTime includes a time component, as it's name suggests. You can use a ValueConverter in your TextBlock binding to strip off the time and display only the date.
At a high level, the ValueConverter will take one type, like a DateTime, and allow you to do some conversions on it. I would probably have it return a formatted string:
String.Format("{0:M/d/yyyy}", dt);
Here's a good intro to ValueConverter, if you haven't used one before.
来源:https://stackoverflow.com/questions/9762463/datepicker-returning-only-date