2011-08-22 116 views
3

我試圖通過將總秒數,即轉換秒到分:秒

1004分鐘到TextBlock的Text屬性綁定:秒,我可以成功地拉我秒從XML,但我不知道如何與Getters和Setters一起工作,所以我可以將我的秒轉換爲分鐘:秒

我看過TimeSpan,我知道它可以做我想問的但我不知道如何編寫getter和setter,因此它會轉換整數值(秒)爲分鐘:秒格式。

這是我在我的課至今

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

任何幫助,將不勝感激,

感謝

約翰

回答

1

會推薦這個轉換器,而不是(因爲前面的兩個答案會給你2:1,當你真的想要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

,並使用它,你在同一時間將其指定爲您的綁定:

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

謝謝哥們,這也救了我從一個巨大的頭痛。 –

+1

當你有2分鐘時,這會給你2:0嗎? –

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