2013-03-05 172 views
0

我有一個組合綁定到項目源。我想將項目的索引顯示爲DisplayMemberPath,而不是綁定對象的任何屬性。顯示組合框中的項目索引

我該如何實現相同。

+2

如何向我們展示您的嘗試......? – Blachshma 2013-03-05 14:11:34

+0

我們可以看到一些代碼嗎?你有什麼嘗試? – 2013-03-05 14:12:13

+0

我試圖寫一個轉換器,但無法弄清楚如何繼續並將項目源傳遞給轉換器。也是適當的將項目源代碼轉換爲 – Mohit 2013-03-05 14:13:06

回答

1

更改ItemsSource到這樣的事情:

public List<Tuple<int,YourObject>> MyItems {get;set;} //INotifyPropertyChanged or ObservableCollection 

public void PopulateItems(List<YourObject> items) 
{ 
    MyItems = items.Select(x => new Tuple<int,YourObject>(items.IndexOf(x),x)).ToList(); 
} 


<ComboBox ItemsSource="{Binding MyItems}" DisplayMemberPath="Item1"/> 
1

你可以用MultiValueConverter做到這一點通過將收集和當前項目中,然後將項目集合中返回項目的索引:

public class ItemToIndexConverter : IMultiValueConverter 
{ 
    public object Convert(object[] value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     var itemCollection = value[0] as ItemCollection; 
     var item = value[1] as Item; 

     return itemCollection.IndexOf(item); 
    } 

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 

的XAML

<ComboBox Name="MainComboBox" ItemsSource="{Binding ComboSourceItems}"> 
    <ComboBox.Resources> 
     <cvtr:ItemToIndexConverter x:Key="ItemToIndexConverter" /> 
    </ComboBox.Resources> 
    <ComboBox.ItemTemplate> 
     <DataTemplate DataType="{x:Type vm:Item}"> 
      <Label> 
       <Label.Content> 
        <MultiBinding Converter="{StaticResource ItemToIndexConverter}"> 
         <Binding Path="Items" ElementName="MainComboBox" /> 
         <Binding /> 
        </MultiBinding> 
       </Label.Content> 
      </Label> 
     </DataTemplate> 
    </ComboBox.ItemTemplate> 
</ComboBox> 

希望這^ h ELPS。

相關問題