views:

308

answers:

1

Morning Guys,

I have a few ComboBoxes bound to List of TimeSpan. I am formatting the TimeSpans using IValueConverter and ItemTemplate. I was wondering if there were an easier way to format the TimeSpans. Here's what I'm currently doing.

public class TimeSpanConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null)
            return string.Empty;

        TimeSpan t = TimeSpan.MinValue;
        TimeSpan.TryParse(value.ToString(), out t);
        return "{0:00}:{1:00}".F(t.Hours,t.Minutes);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return TimeSpan.Parse(value.ToString());
    }

    #endregion
}

<Canvas>
    <Canvas.Resources>
      <bc:TimeSpanConverter x:Key="ts" />
      <DataTemplate x:Key="TimeSpanTemplate">
        <TextBlock Text="{Binding ., Converter={StaticResource ts}}" />
      </DataTemplate>

    </Canvas.Resources>
    <TextBlock Canvas.Left="6"
               Canvas.Top="6"
               Height="21"
               Name="textBlock4"
               Text="Begin"
               Width="40" />

    <TextBlock Canvas.Left="81"
               Canvas.Top="6"
               Height="21"
               Name="textBlock5"
               Text="End"
               Width="40" />
    <ComboBox Canvas.Left="7"
              Canvas.Top="25"
              Height="23"
              Name="TimeBeginCombo"
              ItemTemplate="{StaticResource TimeSpanTemplate}"
              SelectedItem="{Binding TimeBegin}"                  
              Width="68" />
    <ComboBox Canvas.Left="81"
              Canvas.Top="25"
              Height="23"
              Name="TimeEndCombo"
              ItemTemplate="{StaticResource TimeSpanTemplate}"
              SelectedItem="{Binding TimeEnd}"
              Width="68" />

  </Canvas>
</GroupBox>

+2  A: 

Is what you're binding to of type TimeSpan? If so, then the converter can be much simpler

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    if (!(value is TimeSpan))
        return string.Empty;

    TimeSpan t = (TimeSpan)value;
    return "{0:00}:{1:00}".F(t.Hours,t.Minutes);
}

And also, a general remark - are you sure you need to layout your UI on a Canvas and using absolute coordinates? :)

arconaut
Yes, it's a TimeSpan. I like this convert. +1.
Steve