将秒数转换为分钟数:秒

时间:2011-08-22 00:45:15

标签: c# data-binding windows-phone-7

我试图通过转换Total Seconds来绑定TextBlock的Text属性,即

1004分钟:几秒钟,我可以成功地从XML中取出我的秒数,但我不知道如何使用Getters和Setter,这样我就可以将我的秒数转换为分钟:秒数

我查看了TimeSpan,我知道它可以做我要求的但是我不知道如何编写getter和setter所以它会将整数值(秒)转换为Minute:Seconds格式。

到目前为止,这是我班上的内容

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

任何帮助将不胜感激,

感谢

约翰

3 个答案:

答案 0 :(得分:4)

要将其作为您可以执行的财产:

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

虽然你真的应该在你的XAML中这样做,因为正在做的是布局:

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

答案 1 :(得分:2)

使用转换器。

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();
    }
}

答案 2 :(得分:1)

会推荐这个转换器(因为当你真正想要2:01时,前两个答案会给你2:1 -

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

要使用它,您可以在绑定的同时指定它:

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