Search code examples
c#wpfdata-binding

WPF Data Binding - Custom Format for TimeSpan Object


I would like to format the string for a TimeSpan object as the following example: 10h 12m 55s

How can I do this?

xaml

<TextBlock Grid.Column="2" Grid.Row="4" FontSize="20" Text="{Binding Path=ElapsedTime}"/>

xaml.cs

public partial class MainWindow : Window
    { 
        public MainWindow()
        {
            InitializeComponent();
            Streaming StreamingTest = new Streaming();
            DataContext = StreamingTest;
        }
    }

public class Streaming 
   {

   // code

    public TimeSpan ElapsedTime
        {
            get
            {
                return DateTime.Now - startTime;
            }
        }
   }

Solution

  • You can use StringFormat={}{0:h}. but Timespan format doesn't work like Datetime. You can achieve following way.

    1. Convert Timespan to Datetime
    DateTime newElapsedTime = new DateTime() + ElapsedTime;
    

    Then use just like that

    <TextBlock Text="{Binding Path=newElapsedTime, StringFormat={}{0:HH}h {0:mm}m {0:ss}s }" />
    

    Or

    1. Write your own Converter
    public class TimeSpanFormatter:IValueConverter
        {        
    
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                var ts=(TimeSpan)value;
                return string.Format("{0}h {1}m {2}s",ts.Hours,ts.Minutes,ts.Seconds);
            }
    
            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                throw new NotImplementedException();
            }
        }
    

    Then use just like that. Declare formatter in Resource section with name TimeSpanFormatter.

    <TextBlock Text="{Binding Path=ElapsedTime,Converter={StaticResource TimeSpanFormatter}}"></TextBlock>