WPF ComboBox是一种更好的格式化ItemsSource的方法

时间:2010-02-08 17:02:11

标签: wpf combobox format itemssource

Morning Guys,

我有几个ComboBox绑定到TimeSpan列表。我正在使用IValueConverter和ItemTemplate格式化TimeSpans。我想知道是否有更简单的格式化TimeSpans的方法。这就是我目前正在做的事情。

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>

1 个答案:

答案 0 :(得分:2)

你对TimeSpan类型的绑定是什么?如果是这样,那么转换器可以更加简单

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

而且,一般说法 - 您确定需要在Canvas上布局UI并使用绝对坐标吗? :)