Sunday 13 May 2012

Formatting a Data Bound TimeSpan on WP7

Today, I was attempting to format a data bound TimeSpan for our upcoming application using the Custom TimeSpan Format Strings provided on MSDN

Much to my surprise, no matter what I tried, it didn’t appear to format the text, and I’m not the only one to find this.

TimeSpan ts = TimeSpan.FromSeconds(1.24);
string st = string.Format(@"{0:hh\:mm\:ss}", dt);
// st = "00:00:01.2400000"


Clearly the seconds formatting is not working correctly.  And worse, the documentation states that the time separators are not placeholders.


In my case, I know my TimeSpan is always less than 24 hours, so I thought the best solution was to convert it to a DateTime using a converter.


public class TimespanToDateTimeConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
return new DateTime(((TimeSpan) value).Ticks);
}

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


Now in my xaml, I do this to bind to an object named Elapsed:

 


<Grid>
<Grid.Resources>
<fwk:TimespanToDateTimeConverter x:Key="asDate" />
</Grid.Resources> ...
<TextBlock Text="{Binding Elapsed,
Converter={StaticResource asDate},
StringFormat='{0:HH\:mm\:ss\}'}"
/>

</Grid>

This neatly solves the problem, and in the process, delivers locale specific separators as well.

1 comment:

  1. Hi this is really strange, but formatting works with ToString on TimeSpan, I came up with something like this:

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
    if (targetType == typeof(string) && parameter is string && value is TimeSpan)
    {
    TimeSpan timespan = (TimeSpan)value;
    return timespan.ToString((string)parameter);
    }
    return value;
    }

    and in xaml:
    (...)Binding Converter={StaticResource TimeSpanToString}, ConverterParameter='hh\\:mm'

    ReplyDelete