问题
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?
回答1:
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}}"
回答2:
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;
来源:https://stackoverflow.com/questions/18679365/timespan-string-format-in-windows-phone-xaml