Is possible to get a index from a item in a list?

前端 未结 1 1062
悲&欢浪女
悲&欢浪女 2021-01-06 15:48

I mean, I\'ve got a listBox, and I\'m putting in itemsSource property the list. And I want to show also the index in the binding of it.

I have no idea if this is pos

相关标签:
1条回答
  • 2021-01-06 16:17

    There are a few methods for doing this including some workarounds using the AlternationIndex.

    However, since I've used the AlternationIndex for other purposes I like to get a binding for the element index with the following:

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

    Where the converter is defined as:

    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 讨论(0)
提交回复
热议问题