2013-05-05 75 views
0

我试图将TextBlock绑定到TimeSpan,但我需要的格式是这样的,如果TotalMinutes小于60,它应该显示“X min”,否则它应该显示“X h”。有条件的数据绑定到TimeSpan?

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

回答

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(); 
    } 
}