[英]Getting index of an item in an ObservableCollection inside the item
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. 我希望能够在DataTemplate中显示索引值,但我不希望数据由模型或视图模型保留或支持。 In other words, if the order of the items in the OC changes, I don't want to have to recalculate the indexes.
换句话说,如果OC中项目的顺序发生变化,我不想重新计算索引。 The value should be intrinsically tied to the underlying index in the OC.
该值应与OC中的基础索引固有关联。 It is okay if the index is 0-based (in fact, I'd expect it).
如果索引从0开始是可以的(实际上,我希望它)。
One method that others have used is the AlternationIndex AP, but this has its own pitfalls for certain situations. 其他人使用的一种方法是AlternationIndex AP,但这在某些情况下有其自身的缺陷 。
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. 我会使用转换器来做到这一点。
The trick is giving it the source collection, either on the ConverterParameter
or a Dependency Property. 诀窍是在
ConverterParameter
或Dependency Property上为它提供源集合。 At that point, conversion is as simple as using IndexOf
. 此时,转换就像使用
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. 您可以强制键入实现,将格式化的字符串作为数字返回,等等。基本模式如上所述。
This implementation uses the parameter approach, as making a DP is more messy in my view. 这个实现使用参数方法,因为在我看来,DP更加混乱。 Because you can't bind
ConverterParameter
, I have it set to a static resource that is bound to the collection: 因为你无法绑定
ConverterParameter
,所以我将它设置为绑定到集合的静态资源:
<CollectionViewSource x:Key="collectionSource" Source="{Binding Path=MyCollection}" />
...
<TextBlock Text="{Binding Converter={StaticResource ResourceKey=ItemToIndexConverter},
ConverterParameter={StaticResource ResourceKey=collectionSource}}"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.