0

I have an ObservableCollection LogTimeSpan that holds 5 values.

this.LogTimeSpan.Add(TimeSpan.FromMinutes(1));
this.LogTimeSpan.Add(TimeSpan.FromMinutes(10));
this.LogTimeSpan.Add(TimeSpan.FromMinutes(60));
this.LogTimeSpan.Add(TimeSpan.FromHours(12));
this.LogTimeSpan.Add(TimeSpan.FromHours(24));

I use this collection as ItemsSource for a ComboBox in WPF.

<ComboBox Name="cbLogTimeSpan" ItemsSource="{Binding LogTimeSpan}"
                Grid.Row="15" Grid.Column="1" Grid.ColumnSpan="2"
                />

Now my ComboBox looks like:

My ComboBox

What I would like to get is a ComboBox that looks like:

  1. 1 Minute
  2. 10 Minutes
  3. 1 Hour
  4. 12 Hours
  5. 1 Day

What can I do to convert my TimeSpan's that they are shown in the ComboBox as described above?

ck84vi
  • 1,556
  • 7
  • 27
  • 49

1 Answers1

3

One option is to go for a converter, which formats the text of items:

<ComboBox ItemSource="{Binding LogTimeSpan}"
          Grid.Row="15"
          Grid.Column="1"
          Grid.ColumnSpan="2">
  <ComboBox.Resources>
    <ns:TimeSpanConverter x:Key="TimeSpanConverter" />
  </ComboBox.Resources>
  <ComboBox.ItemTemplate>
    <DataTemplate>
      <TextBlock Text="{Binding Path=., Mode=OneTime, Converter={StaticResource TimeSpanConverter}}" />
    </DataTemplate>
  </ComboBox.ItemTemplate>
</ComboBox>

Where you can implement your converter like the following

using System;
using System.Globalization;
using System.Windows.Data;

public class TimeSpanConverter : IValueConverter
{
  public object Convert(object value,
                        Type targetType,
                        object parameter,
                        CultureInfo culture)
  {
    // I am using following extension method here: http://stackoverflow.com/a/4423615/57508
    var timeSpan = (TimeSpan) value;
    var result = timeSpan.ToReadableString();
    return result;
  }

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

If you just need a basic format, you can also use the StringFormat of a binding:

<ComboBox ItemSource="{Binding LogTimeSpan}"
          Grid.Row="15"
          Grid.Column="1"
          Grid.ColumnSpan="2">
  <ComboBox.Resources>
    <ns:TimeSpanConverter x:Key="TimeSpanConverter" />
  </ComboBox.Resources>
  <ComboBox.ItemTemplate>
    <DataTemplate>
      <TextBlock Text="{Binding Path=., Mode=OneTime, StringFormat={}{0:hh\\:mm\\:ss}}" />
    </DataTemplate>
  </ComboBox.ItemTemplate>
</ComboBox>