【问题标题】:Show the item index in combobox在组合框中显示项目索引
【发布时间】:2013-03-06 01:36:15
【问题描述】:

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

我怎样才能达到同样的效果。

【问题讨论】:

  • 向我们展示您的尝试如何...?
  • 我们可以看一些代码吗?你试过什么?
  • 我试图编写一个转换器,但无法弄清楚如何继续并将项目源传递给转换器。将项目源传递给转换是否合适
  • “显示项目索引”是什么意思?显示它在 ComboBox 中显示的位置?还是在您的 ItemsSource 中?
  • 项目索引与项目源索引相同

标签: c# wpf mvvm


【解决方案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>

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    将您的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"/>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-18
      • 1970-01-01
      • 2017-08-09
      相关资源
      最近更新 更多