我想在WPF中使用短日期字符串格式。
我尝试了以下方法:
<TextBlock Text="{Binding Date, StringFormat='Short Date'}" />
如何做到这一点?
试试这个:
<TextBlock Text="{Binding PropertyPath, StringFormat=d}" />
该程序需要.NET 3.5 SP1或更高版本,并且对文化敏感。
注意:大小写敏感。 "d"是短日期格式说明符,而"D"是长日期格式说明符。
有关标准日期和时间格式字符串的完整列表,请参见MSDN页面,并在此MSDN博客文章中了解所有选项的更详细解释。
但是,这里有一个问题-它总是以美国格式输出日期,除非您自己将文化设置为正确的值。
如果不设置此属性,则绑定引擎将使用绑定目标对象的语言属性。在XAML中,默认为“en-US”,或者从页面的根元素(或任何元素)继承该值,如果已经明确设置了该值。
一种实现方法是在代码后台(假设您已将线程的文化设置为正确的值)中进行:
this.Language = XmlLanguage.GetLanguage(Thread.CurrentThread.CurrentCulture.Name);
<TextBlock Text="{Binding PropertyPath, StringFormat=d, ConverterCulture=en-GB}" />
或者使用以下代码来使用英文格式(或混合使用以获得自定义格式):
StringFormat='{}{0:dd/MM/yyyy}'
使用 StringFormat
属性(或在 ContentControl
及其派生类,例如 Label
上使用的 ContentStringFormat
)。
<TextBlock Text="{Binding Date, StringFormat={}{0:d}}" />
请注意,在标准的String.Format
位置参数表示法之前加上{}
可以使大括号在标记扩展语言中被转义。
{}
会让你可以使用 StringFormat='{}创建日期:{0:d}'
,否则会产生意外的结果。 - Brownish Monster以下是我发现有用的一些DateTime字符串格式化示例。摘自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
注意字符串格式中的单引号。 这个不起作用:
Content="{Binding PlannedDateTime, StringFormat={}{0:yy.MM.dd HH:mm}}"
虽然这样做:
Content="{Binding PlannedDateTime, StringFormat='{}{0:yy.MM.dd HH:mm}'}"
只需使用:
<TextBlock Text="{Binding Date, StringFormat=\{0:d\}}" />
<TextBlock Text="{Binding Date, StringFormat= 'Date : {0:d}'}" />
补充Chris的答案,我这样实现了自己简单的CultureAwareBinding
:
public class CultureAwareBinding : Binding
{
public CultureAwareBinding()
{
ConverterCulture = CultureInfo.CurrentCulture;
}
}
然后在 XAML 中这样使用:
<TextBlock
Text="{viewHelpers:CultureAwareBinding Path=ActivationDate, StringFormat=d}"/>
CultureAwareBinding
位于viewHelpers
xmlns中。StringFormat=d
使用了正确的系统CultureInfo
。
CultureAwareBinding
,以帮助解决这个问题。 - Amir Mahdi Nassiri