有没有办法获取 CollectionView 中最近添加的项目的位置或项目。
Reagrds,维克拉姆
订阅CollectionView.CollectionChanged
活动。当事件触发时,查看 的Action
属性NotifyCollectionChangedEventArgs
,如果它等于Add
新添加的项目将包含在NewItems
集合中。通常这将只包含一项,您可以将其保存到适当的变量或类成员中。当您需要知道最近添加的项目是什么时,请阅读此变量。
基于CollectionView
. 在此集合中,存储项目和添加时间之间的映射(以检测新添加的项目订阅CollectionView.CollectionChanged
事件)。在您的集合中定义按时间访问项目的方法public IEnumerable<T> GetItems(DateTime startTime, DateTime endTime)
。
创建一个继承自的源集合INotifyCollectionChanged
,您可以使用ObservableCollection
隐式继承自 INotifyCollectionChanged 的源集合。然后您可以为您的源订阅 CollectionChanged 事件,然后可以查看其中的Action
属性和NewItems
Collection。示例代码 -
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.
}
}