开发者

ObservableCollection auto-index [duplicate]

This question already has answers here: WPF - Bind to Item Index from within ItemTemplate of ItemsControl? (3 answers) Closed 9 years ago.

I've got a list of items that I'm placing in an ObservableCollection which I am then databinding to a datagrid UI created in XAML. One of the columns displ开发者_开发问答ayed is the index of the item in the list. Currently, I am creating a property and binding to it. However, this creates a lot of work when I need to update/add/remove items from the list--I have to go through all affected items and change their property. My question is: Is there a way to automatically display the index of an item in the collection in the UI?


You could use a Converter for your binding where your converter would perform a lookup to find the index. Then, no matter where your item is located at in the collection, you would have the correct index.


Have you considered implementing a viewmodel over the top? Then you could display your ObservableCollection however you want and implement it under the covers

public class IndexedObject
{

    private object _rootObject;
    private int _index;

    public IndexedObject(object rootObject, int index)
    {
        _rootObject = rootObject;
        _index=index;
    }

    public string Value
    {
        get
        {
            return _rootObject.ToString();
        }
    }

    public int Index
    {
        get
        {
            return _index;
        }
    }
}

Then you can implement this property on the class or on the class that displays your ObservableCollection

    ObservableCollection<object> _yourCollection;

    public IEnumerable<IndexedObject> IndexedObjects
    {

        get
        {
            for (int i = 0; i < _yourCollection.Count; i++)
            {
                yield return new IndexedObject(_yourCollection[i], i);
            }
        }
    }

Then you would make the ObservableCollection collectionchanged event notify the program that your IndexedObjects property has changed. Then you can just bind to the IndexedObjects property and use the Index property irrespective of what the actual collection underneath looks like :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜