Question

Is there a way to get the position or the item of the recently added item in CollectionView.

Reagrds, Vikram

Was it helpful?

Solution

Subscribe to the CollectionView.CollectionChanged event. When the event fires, look at the Action property of NotifyCollectionChangedEventArgs, and if it's equal to Add the newly added items will be included inside the NewItems collection. Usually this will contain just one item, which you can save to an appropriate variable or class member. When you need to know what the recently added item was, read this variable.

OTHER TIPS

Implement your own collection based on CollectionView. Inside this collection, store a map between items and time when they were added (to detect newly added items subscribe to CollectionView.CollectionChanged event). Define method in your collection for accessing items by time public IEnumerable<T> GetItems(DateTime startTime, DateTime endTime).

Create a source collection which is inherited from INotifyCollectionChanged, you can use the ObservableCollection which implicitly inherits from INotifyCollectionChanged. And you can subscribe to the CollectionChanged event for your source then and can look at the Action property and NewItems Collection in it. Sample code -

public ObservableCollection<object> Names
{
    get;
    set;
}

private ICollectionView source;
public ICollectionView Source
{
   get
   {
      if (source == null)
      {
         source = CollectionViewSource.GetDefaultView(Names);
         source.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(source_CollectionChanged);
      }
      return source;
    }
}

void source_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
   if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
   {
      // Can play with e.NewItems here.
   }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top