绑定时的StringFormat

绑定时的StringFormat

本文介绍了绑定时的StringFormat的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

视图:

<TextBlock Text="{Binding Date}"/>

我想将日期格式设置为 dd / MM / yyyy,换句话说,没有时间。

I want to format the Date to "dd/MM/yyyy", in other words, without the time.

我尝试过:< TextBlock Text = {Binding Date,StringFormat = {} {0:dd / MM / yyyy} } /> ,但不起作用。

I tried it: <TextBlock Text="{Binding Date, StringFormat={}{0:dd/MM/yyyy}}"/>, but it doesn't work.

给我一​​个错误:在类型中找不到属性'StringFormat'

Gives me an error: The property 'StringFormat' was not found in type 'Binding'.

推荐答案

最好和最简单的方法是使用将日期传递给它的转换器并获取格式化的字符串返回。例如 MyNamespace.Converters 命名空间:

The best and the easiest way would be to use a converter to which you pass the Date and get the formatted string back. In e.g. MyNamespace.Converters namespace:

public class DateFormatConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        if (value == null)
            return null;

        DateTime dt = DateTime.Parse(value.ToString());
        return dt.ToString("dd/MM/yyyy");
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

在您的xaml中,只需引用转换器并添加以下转换器:

And in your xaml just reference the converter and add the following converter:

xmlns:conv="using:MyNamespace.Converters"

在您的xaml页面和page.resources中添加此

in your xaml page and in page.resources add this

<conv:DateFormatConverter x:Name="DateToStringFormatConverter"/>

<TextBlock Text="{Binding Date, Converter={StaticResource DateToStringFormatConverter}"/>

这篇关于绑定时的StringFormat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 13:20