2011-09-02 198 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上的那些方法將是多餘的。 –

相關問題