开发者

How to override a CollectionChanged event in C#?

I am using VS2010 - WPF - C#

I have a listview that takes its items from a source using this instruction :

this.listView1.ItemsSource = CollectionViewSource.GetDefaultView(getTicker());

the problem is that every time the source gets updated, my listview do开发者_Python百科esn't get updated ??

I know I have to do something with the OnCollectionChanged event but I don't know how to do it

Please help me with that . . .


What does the getTicker method does? If each call can return a new collection, maybe you are replacing the collection instead of adding/removing elements to it. I've seen it several times...

Make sure that when you have new items to add (or a whole new collection of items): 1. Clear the collection (the one returned in getTicker) to remove all items 2. Add all the new items to the collection

If you really don't need CollectionviewSource, simply bind an ObservableCollection...


I'm not sure why you are using CollectionViewSource.GetDefaultView(getTicker());

Assuming that getTicker() returns a list of items you can do

this.listView1.ItemsSource = getTicker();

If you want to make sure that your listview updates when the source collection changes then you have to use a collection which implements the INotifyCollectionChanged interface, for example ObservableCollection does that. However you have to make sure that your update your collection on the UI thread.

Update: Here is how you can use ObservableCollection:

var TickerData = new ObservableCollection<MyData>();
this.listView1.ItemsSource = TickerData;

Then you can add/remove items to/from TickerData and the UI will update itself automatically because ObservableCollection implements INotifyCollectionChanged which exposes a CollectionChanged event handler which the listview subscribes to.

I think you might want to have a look at some tutorials on WPF.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜