获得一个项目的索引在一个ObservableCollection项目内 [英] Getting index of an item in an ObservableCollection inside the item

查看:1545
本文介绍了获得一个项目的索引在一个ObservableCollection项目内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够从一个DataTemplate中显示的索引值,但我的不要的数据被持久化或由模型视图模型或支持。换句话说,如果在所述OC变化的项目的顺序,不希望有重新计算的索引。该值应本质绑在OC标的指数。如果该指数是基于0(其实,我希望它),这是好的。

I'd like to be able to display an index value from within a DataTemplate, but I don't want the data to be persisted or backed by the model or viewmodel. In other words, if the order of the items in the OC changes, I don't want to have to recalculate the indexes. The value should be intrinsically tied to the underlying index in the OC. It is okay if the index is 0-based (in fact, I'd expect it).

这是其他人使用的一种方法是的 AlternationIndex AP,但这都有自己的缺陷对于某些情况下

One method that others have used is the AlternationIndex AP, but this has its own pitfalls for certain situations.

最后一个想法:我不禁想转换器将是一个最终的解决方案有帮助的。

One last thought: I can't help but think that a converter is going to be helpful in a final solution.

推荐答案

我会用一个转换器来做到这一点。

I would use a converter to do this.

诀窍是给它的源收集,无论是在 ConverterParameter 或依赖项属性。 。在这一点上,转换为使用的IndexOf 简单

The trick is giving it the source collection, either on the ConverterParameter or a Dependency Property. At that point, conversion is as simple as using IndexOf.

下面是一个示例转换器,做到这一点:

Here's a sample converter that does this:

public class ItemToIndexConverter : IValueConverter
{
    public object Convert(...)
    {
        CollectionViewSource itemSource = parameter as CollectionViewSource;
        IEnumerable<object> items = itemSource.Source as IEnumerable<object>;

        return items.IndexOf(value as object);
    }

    public object ConvertBack(...)
    {
        return Binding.DoNothing;
    }
}

您可以强类型的实现,则返回一个格式化字符串作为一个数等的基本格局将是如上虽然。

You can make the implementation strongly typed, return a formatted string as a number, etc. The basic pattern will be as above though.

这实现使用参数的方法,是把一个DP,在我看来较为凌乱。因为你不能绑定 ConverterParameter ,我把它设置为的静态资源的绑定到集合:

This implementation uses the parameter approach, as making a DP is more messy in my view. Because you can't bind ConverterParameter, I have it set to a static resource that is bound to the collection:

<CollectionViewSource x:Key="collectionSource" Source="{Binding Path=MyCollection}" />

...

<TextBlock Text="{Binding Converter={StaticResource ResourceKey=ItemToIndexConverter}, 
               ConverterParameter={StaticResource ResourceKey=collectionSource}}"/>

这篇关于获得一个项目的索引在一个ObservableCollection项目内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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