Question

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:

  • Why is StringFormat not available in Windows Store Universal Apps?
  • How do i format strings using XAML Code only?


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.

Was it helpful?

Solution

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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top