如何获取当前ItemsControl项的索引?

有没有办法获取WPF当前ItemsControl项的索引?

例如,我想做类似的事情:

         

这样,在此之后,第一个TextBox将显示文本"0" ,第二个"1" ,第三个"2" ...

我建议看看:

WPF ItemsControl ItemsSource中的当前ListItem索引

它解释了如何解决ItemsControl上没有内置Index属性的事实。

编辑:

我尝试了以下代码:

   One Two Three           

并获得一个包含三个TextBlocks的窗口,如:

 [Index is 0] [Index is 1] [Index is 2] 

看一下这个

                  

转换器看起来像这样

  public class conv : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { ObservableCollection lista = (ObservableCollection)values[1]; return String.Concat(lista.IndexOf(values[0].ToString()), " ", values[0].ToString()); } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } 

结果是 在此处输入图像描述

我在这里得到ItemIndex

                                 

和转换器:

 public class GetIndexMultiConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { var collection = (ListCollectionView)values[1]; var itemIndex = collection.IndexOf(values[0]); return itemIndex; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new NotImplementedException("GetIndexMultiConverter_ConvertBack"); } } 

通过这种方式,您可以将每种类型的集合绑定到ItemSource,并且他将更改为ListCollectionView。 因此转换器将适用于不同的收集类型。

 xmlns:componentModel="clr-namespace:System.ComponentModel;assembly=WindowsBase" 

我通过转换器来计算添加元素的索引。

它只适用于一种方式。 如果你以某种方式删除项目或收集改变你应该使用其他东西。 并且您应该为每个集合创建单独的转换器,您需要将哪些元素编入索引。

 public class LineMultiplierConverter : IValueConverter { private int m_lineIndex = 0; Line m_curentLine = null; ///  /// Base value that will be multiplied ///  public double BaseValue { get; set; } public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var line = value as Line; if (line == null) return BaseValue; bool newLine = line != m_curentLine; //check the reference because this method will called twice on one element by my binding if (newLine) { m_lineIndex++; m_curentLine = line; } return BaseValue * m_lineIndex; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } 

我用这种方式在xaml中使用它

  22               

这为我绘制了一个集合中每个元素的行,其中X坐标的BaseValue偏移量。