转换器 - >将日期时间转换为HH:mm:ss格式

转换器 - >将日期时间转换为HH:mm:ss格式

问题描述:

我试图显示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

你可以使用的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