Vikram
Vikram

Reputation: 1627

Get the recently added item in collection view

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

Reagrds, Vikram

Upvotes: 1

Views: 719

Answers (3)

Rohit Vats
Rohit Vats

Reputation: 81233

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.
   }
}

Upvotes: 0

Sergii Vashchyshchuk
Sergii Vashchyshchuk

Reputation: 970

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).

Upvotes: 1

Jon
Jon

Reputation: 437326

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.

Upvotes: 2

Related Questions