2015-11-02 28 views
0

我有一個ObservableCollection LogTimeSpan,它包含5個值。如何轉換組合框中的ItemsSource的TimeSpan值

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

我把這個集合作爲ItemsSource用於WPF中的ComboBox。

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

現在我的組合框的樣子:

My ComboBox

我想獲得一個組合框,看起來像:

  1. 1分鐘
  2. 10分鐘
  3. 1小時
  4. 12小時
  5. 1日

我能做些什麼,以我的轉換時間跨度的,他們都在ComboBox顯示如上所述?

回答

0

這可能會被別人標記爲重複的問題,但這個答案可能會幫助你。

time span to formatted string

+0

你在拉動如何格式化'TimeSpan'到'string',但忽略了這個問題的具體上下文,這是WPF。 –

+0

其涉及的主題相同 –

+0

該問題還顯示OP在格式化項目文本方面掙扎。至少,這並不清楚。另外,請不要包含僅鏈接的答案,請抓住鏈接的本質。 –

3

一種選擇是去一個轉換器,格式項的文本:

<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> 

在這裏你可以實現你的轉換器像下面

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

如果您只需要一個基本的格式,你也可以使用一個綁定的StringFormat

<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> 
相關問題