在 WPF 中的 TextBlock 中使用 StringFormat 格式化日期 [英] Format date with StringFormat in TextBlock in WPF

查看:210
本文介绍了在 WPF 中的 TextBlock 中使用 StringFormat 格式化日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某种原因,我已将日期存储在数据库中而没有斜线.这意味着我有一个像 20110602 这样的日期字段.

I have stored date in database without slashing for some reason . it means that I have a date field like 20110602.

因为我想检索这个日期并将其显示在文本块中,所以我需要一个格式来将此日期显示为带斜杠的普通日期.

As i want to retrieve this date and show it in a textblock I need a formatting to show this date as a normal date with slash.

我如何以这种方式使用 StringFormat ?...有人知道我应该使用什么格式将20110602"转换为 2011/06/02 吗?

How can i use StringFormat in this way ? ... does anyone konw what format should I use to convert "20110602" to 2011/06/02 ?

<TextBlock  Text="{Binding CreatedDate, StringFormat=?????" 

推荐答案

如果您更喜欢实现转换器的路线:

If you perfer the route of implementing a converter:

class dateTimeConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string dateString = (string)value;
        return DateTime.ParseExact(dateString, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

然后在你的 xaml 中

Then in your xaml

<TextBlock Text="{Binding Path=<path>, Converter={StaticResource <dateTimeConverterKey>}, StringFormat=\{0:yyyy/MM/dd\}}"/>

这篇关于在 WPF 中的 TextBlock 中使用 StringFormat 格式化日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆