转换器 - >将DateTime转换为HH:mm:ss格式

时间:2012-04-19 14:46:40

标签: c# wpf

我正在尝试显示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;
    }
}

感谢。

1 个答案:

答案 0 :(得分:4)

您可以使用StringFormat

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

修改

DateTime表示即时,通常表示为日期和时间。

TimeSpan表示时间间隔。

他们有许多类似的方法,尤其是添加或删除小时/分钟/秒的方法,我认为这就是你想要的情况。