item-sourceにコンボバインドしています。バインドされたオブジェクトのプロパティではなく、アイテムのインデックスをDisplayMemberPathとして表示したいと思います。
どうすれば同じことを達成できますか。
コレクションと現在のアイテムを渡してから、アイテム コレクション内のアイテムのインデックスを返すことで、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>
お役に立てれば。
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"/>