有谁知道在 UWP Windows 10 应用程序中使用 x:Bind 时如何格式化日期?
我有一个 TextBlock,它绑定(bind) (x:Bind) 到我的 ViewModel 上从 SQL 读取的 DateTime 属性。我想将输出格式化为“dd/MM/yyy HH:mm (ddd)”。有没有一种简单的方法可以做到这一点?
默认格式是“dd/MM/yyy HH:mm:ss”,我认为这是默认格式。这个可以换吗?
谢谢。
最佳答案
使用 StringFormatConverter
(检查您是否使用了一些已经包含它的库,例如 UWP Toolkit(感谢 @maxp)或旧的 Cimbalino Toolkit):
public class StringFormatConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value == null)
return null;
if (parameter == null)
return value;
return string.Format((string)parameter, value);
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
将其添加到您的页面资源
<Page.Resources>
<converters:StringFormatConverter x:Key="StringFormatConverter" />
</Page.Resources>
然后像这样使用它
<TextBlock Text="{x:Bind Text, Converter={StaticResource StringFormatConverter}, ConverterParameter='{}{0:dd/MM/yyy HH\\\\:mm (ddd)}'}" />
关于c# - 使用 UWP 和 x :Bind 的字符串格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34026332/