条件数据绑定到TimeSpan?

时间:2013-05-05 11:42:24

标签: windows-phone-7 xaml

我正在尝试将TextBlock绑定到TimeSpan,但我需要格式化,以便如果TotalMinutes小于60则应显示“X min”,否则它应显示“X h”。

它有可能吗?那可能需要在xaml中进行tom逻辑测试?

1 个答案:

答案 0 :(得分:3)

您应该使用自定义IValueConverter实施。有几个关于此的教程,例如Data Binding using IValueConverter in Silverlight

您的IValueConverter实施应如下:

public class TimeSpanToTextConverter : IValueConverter
{
    public object Convert(object value, Type targetType,
        object parameter, System.Globalization.CultureInfo culture)
    {
        if (!(value is TimeSpan))
            throw new ArgumentException("value has to be TimeSpan", "value");

        var timespan = (TimeSpan) value;

        if (timespan.TotalMinutes > 60)
            return string.Format("{0} h", timespan.Hours.ToString());
        return string.Format("{0} m", timespan.Minutes.ToString());
    }

    public object ConvertBack(object value, Type targetType, object parameter, 
        System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}