xaml - 如何在 Windows Store Universal App (W8.1 + WP8.1) 中格式化日期?

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

我正在玩新的 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 中不可用.

微软创建了 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 的建议/回答。

    最佳答案

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

  • 使用已格式化的日期作为仅获取 ViewModel 中的属性 .
  • 使用转换器 - 您甚至可以创建 StringFormatConverter,您可以在其中将 DateTime 格式作为 传递转换器参数 . Here's a solution这样的 StringFormatConverter 如何工作。
  • 关于xaml - 如何在 Windows Store Universal App (W8.1 + WP8.1) 中格式化日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23030120/

    相关文章:

    xaml - 向 {x :Bind} in XAML Universal Windows Platform 添加额外的字符串

    xaml - 如何设置 HubSection 标题样式

    maven - 在 Windows 8 上构建 Hadoop 2.6 时出错

    .net - WPF 控件未显示在 WinForms 应用程序的 ElementHost 中

    c# - 如何通过 XAML 手动将静态项目绑定(bind)到 SplitButton (mahapps)

    c# - ForEach循环不改变类的属性

    windows - UWF 提交(如 EWF)

    c# - XAML 菜单项可见但不可选择?

    c# - 我的以 Xamarin 为目标的 UWP 应用缺少选项卡

    c# - 如何使用 Windows Store C++ 在没有窗口句柄的情况下渲染路径几何