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 displayed 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 :)