如何格式化Windows应用商店通用应用程序(W8.1 + WP8.1)中的日期?

Joe*_*oel 10 xaml windows-store-apps windows-8.1 windows-phone-8.1 win-universal-app

我正在使用可用于Windows 8.1和Windows Phone 8.1的新Windows Store Universal App模板,并且想知道如何在XAML代码中格式化字符串.

我尝试了什么(XAML):

 <TextBlock Text="{Binding TestItem.CurrentDate, StringFormat={}{0:MM/dd/yyyy}}" />
Run Code Online (Sandbox Code Playgroud)

问题是StringFormat没有Windows.UI.Xaml.Controls.TextBox.

Microsoft已经创建了一个示例项目,该项目与格式化日期有关.但是那里使用的方法基于(丑陋的)代码.

所以,这是我的问题:

  • 为什么StringFormatWindows Store Universal Apps不提供?
  • 如何仅使用XAML代码格式化字符串?


编辑: 我决定采用转换器解决方案,因为这里感兴趣的是代码:

public class DateConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        if (value == null)
            return null;

        if (!(value is DateTime))
            return null;

        var dateTime = (DateTime)value;

        var dateTimeFormatter = new DateTimeFormatter(YearFormat.Full,
            MonthFormat.Full,
            DayFormat.Default,
            DayOfWeekFormat.None,
            HourFormat.None,
            MinuteFormat.None,
            SecondFormat.None,
            new[] { "de-DE" },
            "DE",
            CalendarIdentifiers.Gregorian,
            ClockIdentifiers.TwentyFourHour);

        return dateTimeFormatter.Format(dateTime);
    }

    public object ConvertBack(object value, Type targetType, object parameter,
        string language)
    {
        throw new NotImplementedException();
    }
}
Run Code Online (Sandbox Code Playgroud)

我很高兴每一条建议如何改进上面的代码,随时评论.

感谢MikaelDúiBolinder和Martin Suchan的建议/答案.

Mar*_*han 7

Windows运行时项目类型中的DataBinding不支持StringFormat属性,您拥有的选项是:

  • 使用已格式化的日期作为ViewModel中的get-only 属性.
  • 使用Converter - 您甚至可以创建StringFormatConverter,您可以将DateTime格式作为ConverterParameter传递.这是一个解决方案,如何使用这样的StringFormatConverter.