2012-04-19 100 views
0

我試圖顯示hh:mm:ss格式,但我總是得到顯示的完整日期。轉換器 - >將日期時間轉換爲HH:mm:ss格式

從我的轉換器類/依賴屬性中是否有錯誤/丟失? 我只收到Datetime.now顯示,如何將其更改爲00:00:00?

我真正想要的是顯示00:00:00作爲初始化。之後它會增加低谷定時器。

XAML:

<ListBox.ItemTemplate> 
<DataTemplate> 
    DownTime="{Binding DownTime, Converter={StaticResource DateTimeConverter}, 
    ConverterParameter=\{0:hh:mm:ss\}} 
</DataTemplate> 
</ListBox.ItemTemplate> 

依賴屬性:

public static readonly DependencyProperty DownTimeProperty = 
    DependencyProperty.Register("DownTime", typeof(DateTime), typeof(RegistrationButton), new UIPropertyMetadata(DateTime.Now)); 

public DateTime DownTime 
    { 
     get { return (DateTime)GetValue(DownTimestandProperty); } 
     set { SetValue(DownTimeProperty, value); } 
    } 

轉換器類:

[ValueConversion(typeof(DateTime), typeof(String))] 
public class DateTimeConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     DateTime dt = (DateTime)value; 
     return dt; 

    } 

    // No need to implement converting back on a one-way binding 
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     string strValue = value as string; 
     DateTime resultDateTime; 
     if (DateTime.TryParse(strValue, out resultDateTime)) 
     { 
      return resultDateTime; 
     } 
     return DependencyProperty.UnsetValue; 
    } 
} 

謝謝秒。

+0

哪個xaml元素實際上包含日期時間綁定? – 2012-04-19 14:48:50

+0

ListBoxItemTemplate ==> DataTemplate – Jackz 2012-04-19 14:50:38

+0

我不是這個意思。我的意思是類似'' – 2012-04-19 14:51:56

回答

4

你可以使用的StringFormat

<TextBlock Text="{Binding DownTime, StringFormat={}{0:"hh:mm:ss"}}" /> 

編輯

DateTime代表某個時刻,通常表示爲一個日期和時間。

TimeSpan表示時間間隔。

他們有很多類似的方法,特別是添加或刪除小時/分鐘/秒的方法,我認爲這就是你想要的這種情況。

+0

我打算說完全一樣的。我目前有它的工作 – 2012-04-19 14:52:34

+0

似乎我真的不希望DateTime.Now作爲初始化,但如何獲得00:00:00作爲開始? – Jackz 2012-04-19 14:53:13

+0

@Jackz看來你應該使用TimeSpan而不是DateTime,因爲你不代表日期,你代表的是一個Interval – dcarneiro 2012-04-19 14:56:17

相關問題