Search code examples
c#xamluwpstring-formattingdate-formatting

StringFormat on Binding


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'.


Solution

  • 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}"/>