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

2019-02-15 13:04发布

问题:

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 possible in WPF. Thanks.

回答1:

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();
    }
}