StringFormat on Binding

developer033 picture developer033 · Jan 11, 2016 · Viewed 20.4k times · Source

View:

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

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

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

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

Answer

CodeNoob picture CodeNoob · Jan 11, 2016

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();
    }
}

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

xmlns:conv="using:MyNamespace.Converters" 

in your xaml page and in page.resources add this

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

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