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

江枫思渺然 提交于 2019-11-30 20:03:07

问题


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


来源:https://stackoverflow.com/questions/7290147/is-possible-to-get-a-index-from-a-item-in-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!