Joel
Joel

Reputation: 4882

How to format a date in an Windows Store Universal App (W8.1 + WP8.1)?

i playing around with the new Windows Store Universal App template which could be used for Windows 8.1 and Windows Phone 8.1 and was wondering how to format strings in XAML code.

What i tried (XAML):

 <TextBlock Text="{Binding TestItem.CurrentDate, StringFormat={}{0:MM/dd/yyyy}}" />

The problem is that StringFormat is not available in Windows.UI.Xaml.Controls.TextBox.

Microsoft has created a sample project which is all about formatting dates. But the approach used there is based on (ugly) code behind.

So, here is my Question:


EDIT: I decided to go with the converter solution, for those of interest here is the code:

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

        if (!(value is DateTime))
            return null;

        var dateTime = (DateTime)value;

        var dateTimeFormatter = new DateTimeFormatter(YearFormat.Full,
            MonthFormat.Full,
            DayFormat.Default,
            DayOfWeekFormat.None,
            HourFormat.None,
            MinuteFormat.None,
            SecondFormat.None,
            new[] { "de-DE" },
            "DE",
            CalendarIdentifiers.Gregorian,
            ClockIdentifiers.TwentyFourHour);

        return dateTimeFormatter.Format(dateTime);
    }

    public object ConvertBack(object value, Type targetType, object parameter,
        string language)
    {
        throw new NotImplementedException();
    }
}

I'm happy for every single advice how to improve the code above, feel free to comment.

Thank you Mikael Dúi Bolinder and Martin Suchan for your suggestion/answer.

Upvotes: 10

Views: 6679

Answers (1)

Martin Suchan
Martin Suchan

Reputation: 10620

DataBinding in Windows Runtime project types does not support StringFormat property, the options you have are:

  • Use already formatted date as a get-only property in your ViewModel.
  • Use Converter - you can even create StringFormatConverter where you can pass the DateTime format as ConverterParameter. Here's a solution how such StringFormatConverter could work.

Upvotes: 7

Related Questions