如何以不同的格式显示DatePicker [英] How to Display DatePicker in different format
问题描述
嗨Firends,
我不熟悉WPF,所以需要一些关于使用WPF的DatePicker控件的帮助。
我得到一个XML文档,其中一个字段是Date字段,如下所示:
Hi Firends,
I am not conversant with WPF so need some help about using DatePicker control of WPF.
I am getting an XML document in which one of the field is Date field as below:
<Students>
<Student>
<Name>John</Name>
<DateOfBirth>1990-12-05</DateOfBirth>
</Student>
<Student>
<Name>Mike</Name>
<DateOfBirth>1980-05-09</DateOfBirth>
</Student>
</Students>
日期始终采用yyyy-MM-dd格式。但我需要以dd / MM / yyyy格式在DatePicker中显示日期。此外,当用户从DatePicker编辑日期时,我需要以相同的格式将日期保存在XML中,即yyyy-MM-dd。
请让我知道怎么做。
问候
Aseem
The date always comes in the format "yyyy-MM-dd". But I need to display the date in DatePicker in format "dd/MM/yyyy". Also when user edit the date from DatePicker, I need to save the date back in the XML in the same format i.e. "yyyy-MM-dd".
Please let me know how to do that.
Regards
Aseem
推荐答案
最好的想法是让学生班级有Name和DateOfBirth属性。然后在你的XAML中,你需要做的就是将DatePicker绑定到DOB属性并像这样设置StringFormat
The best idea is to have a student class with Name and DateOfBirth Properties. Then in your XAML, all you need to do is bind the DatePicker to the DOB property and set the StringFormat like this
<DatePicker SelectedDate="{Binding Path=DateOfBirth,StringFormat='dd/MM/yyy'}" />
然后你可以在Student类或Data Access类中使用Save方法以正确的格式保存DOB属性。
Then you could have a Save method in your Student class or Data Access class that saves the DOB property in the correct format.
格式化字符串以便保存XML:
To format the string for saving in XML:
String.Format("{0:yyyy-MM-dd}", dt);
您应该可以通过更新文化来覆盖默认格式:
You should be able to override your default format by updating the culture:
CultureInfo ci = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name); ci.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd";
Thread.CurrentThread.CurrentCulture = ci;
然后每当你输出shortdate时它应该是正确的格式
Then whenever you output shortdate it should be the right format
dt.ToShortDateString();
设置文化信息应该允许您直接从字符串中获取日期:
Setting the culture information should allow you to get date directly from the string:
var x = DateTime.Parse("2000-12-30");
您应该可以通过更新文化来覆盖默认格式:
You should be able to override your default format by updating the culture:
CultureInfo ci = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name);
ci.DateTimeFormat.ShortTimePattern = "HH.mm";
Thread.CurrentThread.CurrentCulture = ci;
然后每当你输出shortdate时它应该是正确的格式
Then whenever you output shortdate it should be the right format
这篇关于如何以不同的格式显示DatePicker的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!