Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 but 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

like image 645
John Antony Daniel Nolan Avatar asked Dec 28 '22 15:12

John Antony Daniel Nolan


2 Answers

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>
like image 126
shf301 Avatar answered Jan 06 '23 00:01

shf301


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>
like image 37
Henry C Avatar answered Jan 06 '23 01:01

Henry C