开发者

Converting Seconds to Minutes:Seconds

I am trying to bind a TextBlock's Text property by converting the Total Seconds i.e

1004 to Minutes:Seconds and I can successfully pull my Seconds from the XML but I dont know how to work with Getters and Setters so I can convert my Seconds to Minutes:Seconds

I had a look at TimeSpan and I know it can do what I ask 开发者_如何学Gobut I dont know how to write the getter and setter so it will convert the integer values (seconds) to a Minute:Seconds format.

This is what I have in my Class so far

public class Stats 
{
 public TimeSpan Time {get;set;}
}

any help would be greatly appreciated,

thanks

John


To do it as a property you can do:

public class Stats {
   public TimeSpan Time { get; set; }
   public string TimeFormated { get { return Time.TotalMinutes + ":" + Time.Seconds; } }
}

Although you really should do that in your XAML since the what are doing is layout:

<StackPanel Orientation="Horizontal">
  <TextBlock Text={Binding Time.TotalMinutes}" />
  <TextBlock Text=":" />
  <TextBlock Text=={Binding Time.Seconds}" />
</StackPanel>


Would recommend this converter instead (since the two previous answers will give you 2:1 when you really want 2:01 -

public class FriendlyTimeConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        TimeSpan ts = TimeSpan.FromSeconds((int)value);
        return String.Format("{0}:{1:D2}", ts.Minutes, ts.Seconds);                
    }

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

}

Note the :D2 specifier for format strings.

And to use it, you specify it at the same time as your binding:

<phone:PhoneApplicationPage.Resources>
    <util:FriendlyTimeConverter x:Key="FriendlyTimeConverter"/>
</phone:PhoneApplicationPage.Resources>

...

<TextBlock Text="{Binding timeRemaining, Converter={StaticResource FriendlyTimeConverter}}" Name="TimerDisplay" Grid.Column="4" HorizontalAlignment="Right" Margin="12,0" Style="{StaticResource PhoneTextTitle2Style}"></TextBlock>


Use a converter.

XAML:

<phone:PhoneApplicationPage.Resources>
    <classes:TimeSpanConverter x:Key="c" />
</phone:PhoneApplicationPage.Resources>
...
<TextBlock Text="{Binding Time, Converter={StaticResource c}}" />

C#:

public class TimeSpanConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var time = (TimeSpan) value;
        return time.TotalMinutes + ":" + time.Seconds;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜