4

I'm attempting to apply a XAML StringFormat to a TimeSpan property.

NOTE This question applies to Windows Phone.

For WPF, the correct syntax is:

Text="{Binding ElapsedTime,StringFormat={}{0:m\\:ss}}"

For Silverlight, it needs single-quotes:

Text="{Binding ElapsedTime,StringFormat='{}{0:m\\:ss}'}"

But for Windows Phone, no matter what I have tried, the output is always the full "00:00:00.0000000".

  • StringFormat='m\\:ss'
  • StringFormat='{}{0:m\\:ss}'
  • StringFormat='m\:ss'
  • StringFormat=m\\:ss

Have I somehow missed the correct permutation, or is this just not possible for some reason in Windows Phone?


Update

I used a workaround (answer below), but would still like an explanation of the weirdness, if anyone knows. (I say "weirdness" because StringFormat works perfectly well with DateTime properties, just not with TimeSpan ones.)

Update #2

A very similar question from 2010. Maybe this is just an issue with older and/or "compact" versions of .Net. Or would this answer (StringFormat=\{0:h\\:mm\}) work?

Community
  • 1
  • 1
McGarnagle
  • 101,349
  • 31
  • 229
  • 260

2 Answers2

3

Here is something that worked for me for Timespan property I created called ElapsedTime.

Text="{Binding ElapsedTime,StringFormat={}{0:mm\\:ss}}"

Full format

Text="{Binding ElapsedTime,StringFormat={}{0:dd\\.hh\\:mm\\:ss}}"
Mitul
  • 9,734
  • 4
  • 43
  • 60
  • Without the single-quotes, I can't compile. Visual Studio is showing an error "unexpected token after end of markup". I suspect you tested this using WPF? – McGarnagle Sep 09 '13 at 16:42
  • Yes it was WPF. Could it be that using a single m instead mm be a problem? – Mitul Sep 09 '13 at 17:01
3

I ended up using a workaround.

<TextBlock Text="{Binding DurationStr}" />

With a new property in the view-model:

public string DurationStr
{
    get { return Duration.ToString(@"m\:ss"); }
}

public TimeSpan Duration
{
    get { return _duration; }
    set
    {
        _duration = value;
        RaisePropertyChanged("Duration");
        RaisePropertyChanged("DurationStr");
    }
}
private TimeSpan _duration;
McGarnagle
  • 101,349
  • 31
  • 229
  • 260