Delen via


Windows 8 getting StringFormat functionality

So in WPF and windows phone you were able to StringFormat your bindings so you can display your binded data in different formats so for example if you have a datetime variable and you want only to display the minutes or the month name using StringFormat you can easily achieve that. But that functionality was missing from windows 8, so In order to get around that we will have to implement a value converter.

The Converter

 public class StringFormatConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            //No value provided
            if (value == null)
            {
                return null;
            }
            // No format provided.
            if (parameter == null)
            {
                return value;
            }

            return String.Format((String)parameter, value);
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            return value;
        }
    }

The Page Resources

<common:StringFormatConverter x:Key="StringFormatConverter" />

 
 

Just added a reference to the converter in your page resources.

Using the StringFormat Converter

 <TextBlock Text="{Binding SomeDateTime, Converter={StaticResource StringFormatConverter},
  ConverterParameter='{}{0:dd MMM yyyy}'}" />

And now you just pass the Format string to the ConverterParameter and you are done. For more Custom Date and Time Format Strings follow this link.