views:

53

answers:

1

I have a TabControl which is having 2 TabItems. Each of these two TabItems is having 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. What may be the possible reason for this?

A: 

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.

Ciemnl