2011-09-02 133 views
1

我的意思是,我有一个列表框,并且我将itemsSource属性放入列表中。而且我还想在它的绑定中显示索引。是否有可能从列表中的项目获取索引?

我不知道这是可能的WPF。谢谢。

+0

几乎任何事情都可能在WPF中 - 使用正确的XAML /代码隐藏组合 –

回答

7

有几种方法可以做到这一点,包括some workarounds using the AlternationIndex

但是,因为我已经用于其他目的的AlternationIndex我希望得到的元素索引的绑定有以下:

<MultiBinding Converter="{StaticResource indexOfConverter}"> 
    <Binding RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}" /> 
    <Binding Path="."/> 
</MultiBinding> 

当转换器被定义为:

public class IndexOfConverter : IMultiValueConverter 
{ 
    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     if (Designer.IsInDesignMode) return false; 

     var itemsControl = values[0] as ItemsControl; 
     var item = values[1]; 
     var itemContainer = itemsControl.ItemContainerGenerator.ContainerFromItem(item); 

     // It may not yet be in the collection... 
     if (itemContainer == null) 
     { 
      return Binding.DoNothing; 
     } 

     var itemIndex = itemsControl.ItemContainerGenerator.IndexFromContainer(itemContainer); 
     return itemIndex; 
    } 

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) 
    { 
     return targetTypes.Select(t => Binding.DoNothing).ToArray(); 
    } 
} 
+0

'ItemsControl.Items.IndexOf(values [1])''? –

+0

我相信'Items'集合包含UIElements而不是绑定的实际项目。 – Reddog

+0

不,它不会,如果是这样的话,ItemContainerGenerator上的那些方法将是多余的。 –

相关问题