WPF:我如何钩到一个ListView的的ItemsSource CollectionChanged通知? [英] WPF: How do I hook into a ListView's ItemsSource CollectionChanged notification?

查看:453
本文介绍了WPF:我如何钩到一个ListView的的ItemsSource CollectionChanged通知?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个的ListView 这是数据绑定到的ObservableCollection ...

I have a ListView that is databound to an ObservableCollection ...

<ListView x:Name="List1" ItemsSource="{Binding MyList}" />

我似乎无法找到触发的收集发生变化时无论如何,所以我想,不知怎的,我需要挂接到collectionchanged通知不知何故?我真的不知道该怎么做。

I can't seem to find any event that are triggered when the collection changes, so I'm thinking that somehow I need to hook into the collectionchanged notification somehow? I'm not really sure how to do that.

基本上,当集合改变我想要做的超出了ListView中已经做额外的工作在更新它的列表中。

Basically, when the collection changes I want to do additional work beyond what the ListView already does in updating it's list.

推荐答案

默认情况下,的ItemsSource 的类型为<一个href=\"http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx\"><$c$c>IEnumerable.您需要先转换为具有访问<一个类型href=\"http://msdn.microsoft.com/en-us/library/system.collections.specialized.inotifycollectionchanged.collectionchanged.aspx\"><$c$c>CollectionChanged事件,然后添加一个处理该事件。

By default the ItemsSource is of type IEnumerable. You need to first cast to a type that has access to the CollectionChanged event, then add a handler for that event.

((INotifyCollectionChanged)List1.ItemsSource).CollectionChanged +=
    new NotifyCollectionChangedEventHandler(List1CollectionChanged);

public void List1CollectionChanged(Object sender, NotifyCollectionChangedEventArgs e)
{
    //You're logic here
}



注:我投它<一个href=\"http://msdn.microsoft.com/en-us/library/system.collections.specialized.inotifycollectionchanged.aspx\"><$c$c>INotifyCollectionChanged在我的例子,但你真的可以把它转换为实现该任何对象。虽然,作为最佳实践,您应该转换为最通用的类​​型,让你获得你所需要的方法/属性/事件。所以,当你将其转换为的ObservableCollection ,你不需要。 INotifyCollectionChanged 包含你所需要的活动,如果你决定使用一些其他类型的集合,实现它,这将继续工作,而转换为一个的ObservableCollection 表示,如果有一天你决定,你是名单现在键入 MyOwnTypeOfObservableCollectionNotDerivedFromObservableCollection 比,这将打破。 ;)


Note: I cast it to INotifyCollectionChanged in my example, but you can really cast it to any object that implements that. Though, as a best practice, you should cast to the most generic type that gives you access to the methods/properties/events you need. So, while you can cast it to an ObservableCollection, you don't need to. INotifyCollectionChanged contains the event you need and if you ever decide to use some other type of collection that implements it, this will continue to work, whereas casting to an ObservableCollection means that if you one day decide that you're list is now of type MyOwnTypeOfObservableCollectionNotDerivedFromObservableCollection than this will break. ;)

P.S。这应该在XAML code-落后。

P.S. This should go in the xaml code-behind.

这篇关于WPF:我如何钩到一个ListView的的ItemsSource CollectionChanged通知?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆