我想在WPF中使用短日期命名字符串格式。
我尝试过类似的事情:
<TextBlock Text="{Binding Date, StringFormat='Short Date'}" />
怎么做?
答案 0 :(得分:158)
试试这个:
<TextBlock Text="{Binding PropertyPath, StringFormat=d}" />
对文化敏感,需要.NET 3.5 SP1或更高版本。
注意:这是区分大小写的。 “d”是short date format specifier而“D”是long date format specifier。
MSDN page on Standard Date and Time Format Strings上有完整的字符串格式列表,以及this MSDN blog post上所有选项的更全面说明
但是,有一个问题 - 除非您自己将文化设置为正确的值,否则它始终以美国格式输出日期。
如果未设置此属性,则绑定引擎将使用绑定目标对象的语言属性。在XAML中,如果已明确设置,则默认为“en-US”或从页面的根元素(或任何元素)继承值。
执行此操作的一种方法是在后面的代码中(假设您已将线程的文化设置为正确的值):
this.Language = XmlLanguage.GetLanguage(Thread.CurrentThread.CurrentCulture.Name);
另一种方法是在绑定中设置转换器文化:
<TextBlock Text="{Binding PropertyPath, StringFormat=d, ConverterCulture=en-GB}" />
虽然这不允许您本地化输出。
答案 1 :(得分:40)
或者将其用于英语(或混合自定义)格式:
StringFormat='{}{0:dd/MM/yyyy}'
答案 2 :(得分:21)
使用StringFormat
属性(ContentStringFormat
及ContentControl
及其衍生产品,例如Label
。
<TextBlock Text="{Binding Date, StringFormat={}{0:d}}" />
注意标准{}
位置参数表示法之前的String.Format
允许使用标记扩展语言转义大括号。
答案 3 :(得分:8)
我发现一些有用的DateTime StringFormat示例。取自C# Examples
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);
String.Format("{0:y yy yyy yyyy}", dt); // "8 08 008 2008" year
String.Format("{0:M MM MMM MMMM}", dt); // "3 03 Mar March" month
String.Format("{0:d dd ddd dddd}", dt); // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}", dt); // "4 04 16 16" hour 12/24
String.Format("{0:m mm}", dt); // "5 05" minute
String.Format("{0:s ss}", dt); // "7 07" second
String.Format("{0:f ff fff ffff}", dt); // "1 12 123 1230" sec.fraction
String.Format("{0:F FF FFF FFFF}", dt); // "1 12 123 123" without zeroes
String.Format("{0:t tt}", dt); // "P PM" A.M. or P.M.
String.Format("{0:z zz zzz}", dt); // "-6 -06 -06:00" time zone
答案 4 :(得分:4)
只需使用:
<TextBlock Text="{Binding Date, StringFormat=\{0:d\}}" />
答案 5 :(得分:3)
如果你想添加一个带有值的字符串,请使用:
<TextBlock Text="{Binding Date, StringFormat= 'Date : {0:d}'}" />
答案 6 :(得分:1)
请注意字符串格式的单引号。 这不起作用:
Content="{Binding PlannedDateTime, StringFormat={}{0:yy.MM.dd HH:mm}}"
这样做的时候:
Content="{Binding PlannedDateTime, StringFormat='{}{0:yy.MM.dd HH:mm}'}"