简体   繁体   English

在WP7上格式化XAML中的日期

[英]Formatting a date in XAML on WP7

Is there a way to format a date using XAML for Windows Phone 7? 有没有办法使用XAML为Windows Phone 7格式化日期?

If tried using: 如果尝试使用:

<TextBlock Text="{Binding Date, StringFormat={}{0:MM/dd/yyyy}}" />

But I get the error: 但我得到错误:

The property 'StringFormat' was not found in type 'Binding' 在'Binding'类型中找不到属性'StringFormat'

Within SL4 this is possible... 在SL4内这是可能的......

<TextBlock Text="{Binding Date, StringFormat='MM/dd/yyyy'}}"/>

...within SL3 you would need to make use of an IValueConverter . ...在SL3中你需要使用IValueConverter

public class DateTimeToStringConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return String.Format("{0:MM/dd/yyyy}", (DateTime)value);
    }

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

If you wanted a more robust approach you could make use of the ConverterParameter . 如果你想要一个更强大的方法,你可以使用ConverterParameter

    public class DateTimeToStringConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
                if (parameter == null)
                    return ((DateTime)value).ToString(culture);
                else
                    return ((DateTime)value).ToString(parameter as string, culture);
        }

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

Then in your XAML you would first define the converter as a resource... 然后在您的XAML中,您首先将转换器定义为资源...

<namespace:DateTimeToStringConverter x:Key="MyDateTimeToStringConverter"/>

..then reference it along with an acceptable parameter for formatting the DateTime value... ..然后引用它以及用于格式化DateTime值的可接受参数...

<TextBlock Text="{Binding Date, 
         Converter={StaticResource MyDateTimeToStringConverter}, 
         ConverterParameter=\{0:M\}}"/>

As far as I'm aware StringFromat is Silverlight 4 function, Silverlight for Windows Phone 7.0 is basically Silverlight 3 + some extras. 据我所知,StringFromat是Silverlight 4的功能,Silverlight for Windows Phone 7.0基本上是Silverlight 3 +一些附加功能。 I guess no then. 我想没有。

This is probably what you are looking for. 这可能就是你要找的东西。 RelativeDateTimeConverter RelativeDateTimeConverter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM