使用 UWP 和 x:Bind 的字符串格式

String format using UWP and x:Bind

有谁知道在 UWP Windows 10 应用程序中使用 x:Bind 时如何格式化日期?

我有一个 TextBlock,它绑定 (x:Bind) 到我的 ViewModel 上的 DateTime 属性,它是从 SQL 读取的。我想将输出格式化为 "dd/MM/yyy HH:mm (ddd)"。有没有简单的方法可以做到这一点?

默认格式是 "dd/MM/yyy HH:mm:ss",我认为这是默认格式。这个可以换吗?

谢谢。

使用 StringFormatConverter(检查您是否使用了一些已经包含它的库,例如 UWP Toolkit (thanks, @maxp) or the older 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)}'}" />

你可以使用

{x:Bind ViewModel.DateTimeProperty.ToString("....")}

Function binding 比 classic Converter:

好得多
 <TextBlock Text="{x:Bind DateTimeToString(MyDateTime,'dd/MM/yyy HH\\:mm (ddd)')}" />

后面的代码(可以单独放在class):

//"Converter"
public string DateTimeToString(DateTime dateTime, string format) => dateTime.ToString(format);

public DateTime MyDateTime { get; set; } = DateTime.Now;

为什么比classic转换器好?

  • 较短->无煮辫码
  • 强类型 -> 在构建时检测异常。

类似于后面的代码

xmlns:globalization="using:System.Globalization"
...

{x:Bind ViewModel.DateTimeProperty.ToString('dd/MM/yyy HH:mm (ddd)', globalization:DateTimeFormatInfo.InvariantInfo)}

...