0

item-sourceにコンボバインドしています。バインドされたオブジェクトのプロパティではなく、アイテムのインデックスをDisplayMemberPathとして表示したいと思います。

どうすれば同じことを達成できますか。

4

2 に答える 2

2

コレクションと現在のアイテムを渡してから、アイテム コレクション内のアイテムのインデックスを返すことで、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>

お役に立てれば。

于 2013-03-05T17:36:15.590 に答える
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"/>
于 2013-03-05T14:50:49.120 に答える