【发布时间】: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}}" />
问题是StringFormat 在Windows.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