C# 在组合框中显示项目索引

C# 在组合框中显示项目索引,c#,wpf,mvvm,C#,Wpf,Mvvm,我有一个项目源的组合绑定。我想将项的索引显示为DisplayMemberPath,而不是绑定对象的任何属性 如何实现同样的效果。将您的项目资源更改为以下内容: public List<Tuple<int,YourObject>> MyItems {get;set;} //INotifyPropertyChanged or ObservableCollection public void PopulateItems(List<YourObject> items

我有一个项目源的组合绑定。我想将项的索引显示为DisplayMemberPath,而不是绑定对象的任何属性


如何实现同样的效果。

将您的
项目资源更改为以下内容:

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"/>
public List MyItems{get;set;}//INotifyPropertyChanged或ObservableCollection
公共void PopulateItems(列表项)
{
MyItems=items.Select(x=>newtuple(items.IndexOf(x,x)).ToList();
}

将您的
项目资源更改为以下内容:

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"/>
public List MyItems{get;set;}//INotifyPropertyChanged或ObservableCollection
公共void PopulateItems(列表项)
{
MyItems=items.Select(x=>newtuple(items.IndexOf(x,x)).ToList();
}

您可以使用多值转换器,通过传入集合和当前项目,然后返回项目集合中项目的索引来完成此操作:

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



希望这会有所帮助。

您可以使用多值转换器,通过传入集合和当前项目,然后返回项目集合中项目的索引:

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



希望这能有所帮助。

让我们看看您尝试了什么…?我们能看一些代码吗?你试过什么?我试过写一个转换器,但不知道如何继续并将项目源传递给转换器。将项目源传递给Converted是否合适?什么是“项目的显示索引”?是否显示它在组合框中显示的位置?或者在您的ItemsSource中?item的索引与items Source中的索引相同如何向我们展示您尝试了什么…?我们可以看到一些代码吗?你试过什么?我试过写一个转换器,但不知道如何继续并将项目源传递给转换器。将项目源传递给Converted是否合适?什么是“项目的显示索引”?是否显示它在组合框中显示的位置?或者在您的ItemsSource?项目的索引与项目源中的索引相同