【问题标题】:How to format a date in an Windows Store Universal App (W8.1 + WP8.1)?如何在 Windows 应用商店通用应用程序 (W8.1 + WP8.1) 中格式化日期?
【发布时间】:2014-05-26 15:27:00
【问题描述】:

我正在使用新的 Windows 应用商店通用应用程序模板,该模板可用于 Windows 8.1 和 Windows Phone 8.1,并且想知道如何在 XAML 代码中格式化字符串。

我尝试了什么(XAML):

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

问题是StringFormatWindows.UI.Xaml.Controls.TextBox 中不可用。

Microsoft 已经创建了一个sample project,它是关于格式化日期的。但是那里使用的方法是基于(丑陋的)代码。

所以,这是我的问题:

  • 为什么StringFormat 在 Windows 应用商店通用应用中不可用?
  • 如何仅使用 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();
    }
}

对于如何改进上述代码的每一条建议,我都很高兴,请随时发表评论。

感谢 Mikael Dúi Bolinder 和 Martin Suchan 的建议/回答。

【问题讨论】:

  • 也许你应该创建一个转换器?
  • 是的,这是一个选择,但我不想在我之前这样做,因为没有其他(更好的)方法可以做到这一点。
  • 您是如何在标记中链接转换器的?我所有的静态资源、相对..等组合都失败了。附带说明:我觉得缺少 StringFormat 很荒谬。现在是 2014 年和 .NET 4.5。在他们通过 Windows Phone 8.1 举行的所有会议中,没有人提出 DataBound 控件的日期格式?
  • @JohnK:太真实了,我不再了解微软了。我最近开始失去信心。
  • 同意 100%,我为 WP8.1 编写的代码越多,我也越怀疑他们是否知道自己在做什么。我已经浪费了几个小时试图以 .ToString("dd/mm/yyyy") 的形式做一些我认为需要几秒钟的事情,我现在已经放弃了,现在正在等待这篇文章的帮助。嘘!

标签: xaml windows-store-apps windows-8.1 windows-phone-8.1 win-universal-app


【解决方案1】:

Windows 运行时项目类型中的 DataBinding 不支持 StringFormat 属性,您可以选择:

  • 在您的 ViewModel 中将已格式化的日期用作只能获取的属性
  • 使用 Converter - 您甚至可以创建 StringFormatConverter,您可以在其中将 DateTime 格式作为 ConverterParameter 传递。 Here's a solution 这样的 StringFormatConverter 是如何工作的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-22
    • 2014-12-05
    相关资源
    最近更新 更多