如果您想在使用 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}}" />