可以从一个项指数列表中? [英] Is possible to get a index from a item in a list?

查看:131
本文介绍了可以从一个项指数列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的意思是,我有一个列表框,而我在ItemsSource属性把清单。而且我想也显示在它的结合的索引。

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.

我不知道这是否可能在WPF。谢谢你。

I have no idea if this is possible in WPF. Thanks.

推荐答案

有这样做的,包括的一些解决方法使用AlternationIndex

不过,因为我已经用于其他目的的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();
    }
}

这篇关于可以从一个项指数列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆