Getting index of an item in an ObservableCollection inside the item

后端 未结 1 1549
情话喂你
情话喂你 2021-01-18 22:50

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

1条回答
  •  鱼传尺愫
    2021-01-18 23:19

    I would use a converter to do this.

    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 items = itemSource.Source as IEnumerable;
    
            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. Because you can't bind ConverterParameter, I have it set to a static resource that is bound to the collection:

    
    
    ...
    
    
    

    0 讨论(0)
    提交回复
    热议问题