开发者

Does memory leak if we set ItemSource property of a control to null in WPF?

开发者 https://www.devze.com 2023-01-08 01:46 出处:网络
I have a TabC开发者_运维技巧ontrol which havs two TabItems. Each of these two TabItems has a listbox. On the SelectionChanged event handler I am setting ItemSource property of the appropriate ListBox

I have a TabC开发者_运维技巧ontrol which havs two TabItems. Each of these two TabItems has a listbox. On the SelectionChanged event handler I am setting ItemSource property of the appropriate ListBox to null and populating the other one with a Collection. Now when I keep on selecting each Tab there is a memory spike. Why is this?


Try not emptying the lists when you change tabs, I don't think WPF will attempt to draw the list if it is not being displayed. When I need to make a listbox/ itemscontrol display a collection of objects I do this:

//have all the usual usings and
using System.ComponentModel
using System.Collections.ObjectModel
class Bar : INotifyPropertyChanged
{
   //make your properties setters call PropertyChanged
}
class Bars : ObservableCollection<Bar>
{
}

then set your listbox to have ItemsSource as your instance of Bars and use a data template to display each Bar. This means that you never have to set ItemsSource again (becuase ObservableCollection will automatically tell the listbox to update when something changes) which I am guessing is where the leak is occuring. By not repetedly changing ItemsSource the program will probably be more efficient but that is not a guarantee :) if you get desperate, Red-Gate do a free .net reflector so you can have a peek at what your ListBox is actually doing.

Another problem could be that the listbox isn't virtualizing properly but I seem to remember that ListBoxes do virtualize but you will need a second oppinion for that.


Even if it doesn't appear this way but a TabControl is just a normal ItemsControl. http://msdn.microsoft.com/en-us/library/system.windows.controls.tabcontrol.aspx

Setting the selected Item to a Tab the Visual Tree is completly built from its containing Content.

If you have a freezing Page try to load your data asynchronously in a Task Factory.

Also maybe clear your Collection instead of setting it to null :)

0

精彩评论

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