如何在 XAML 中格式化 TimeSpan

如果您想在使用 Content 属性的 Label 中使用 StringFormat,您可以使用ContentStringFormat来格式化您的时间跨度:

<Label Content={Binding MyTimespan}" ContentStringFormat="{}{0:hh}:{0:mm}:{0:ss}"

TextBlock 

<TextBlock Text="{Binding MyTime,StringFormat=`Time values are {0:hh\\:mm}`}"/>

但如果您希望完全自由地将 TimeSpan 转换为字符串,同时保持干净的 XAML 样式,还可以选择创建一个简单的 IValueConverter : 

using System;
using System.Windows.Data;

namespace Bla
{
    [System.Windows.Data.ValueConversion(typeof(TimeSpan), typeof(string))]
    public class TimespanToSpecialStringConverter : IValueConverter
    {
        #region IValueConverter Members
        public object Convert(object value, Type targetType, object parameter,
        System.Globalization.CultureInfo culture)
        {
            if (targetType != typeof(string))
                throw new InvalidOperationException("The target must be a string");                
            var timeSpan = (TimeSpan)value;
            string minutes = timeSpan.Minutes < 10 ? "0" + timeSpan.Minutes : ""+timeSpan.Minutes;
            string seconds = timeSpan.Seconds < 10 ? "0" + timeSpan.Seconds : "" + timeSpan.Seconds;
            return "" + timeSpan.TotalHours + ":" + minutes + ":" + seconds;
        }

        public object ConvertBack(object value, Type targetType, object parameter,
        System.Globalization.CultureInfo culture)
        {
            if (targetType != typeof(TimeSpan))
                throw new InvalidOperationException("The target must be a TimeSpan");                
            return TimeSpan.Zero;
        }
        #endregion
    }
}

 然后,它可能有,例如用户控件中的 StaticResource :

<UserControl.Resources>
    <local:TimespanToSpecialStringConverter x:Key="TimespanToSpecialStringConverter" />
</UserControl.Resources>

 最后在典型的数据绑定中应用 TimespanToSpecialStringConverter :

<TextBlock Text="{Binding Path=ATimespanDependencyProperty, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource TimespanToSpecialStringConverter}}" />

TimeSpan 资料

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值