Attached Behavior on Virtualised Items

Aug 5, 2010 at 6:20 AM


I have a requirement to manage memory for WPF applications. Before I do that I had a few questions...

1. Attached behaviors which hook the UI control events, leave the event handler references dangling even after the control is no longer usable on the UI? (such as a virtualised item of a item control)
2. Does specifying attached properties in Styles make any difference?
 Triggers may be?

3. When we use dockable contents (such as a TabItem) and close the dockable content after use, what is the guarantee that the content UI will be freed from the memory in timely manner?
4. Does .Net 4.0 has some betterments in tems of memory management of unusable UI contents?

Now my observations are ...

1. Attached behaviors do not unhook the event handlers automatically unless explicitly done. which means even if the ui control was not usable on the UI, it must remain in the memory. (plz correct me if I am wrong)
2. Weak references in attached behaviors fail to work in the case of template generated controls i.e. virtualised items from the itemscontrol.
3. Any unloading of the UI contents from any WPF container doesnt gurantee its successful removal from memory.
4. .Net 4.0 framework sets NamedObject as the datacontext to disconnected items (i.e. the virtualised items from itemscontrols) whereas .Net 3.5 framework keeps the data context as it is.

So using the above information I tried doing memory profiling for 3 applications (.Net 3.5 app in VS 2008, .Net 3.5. app in VS2010 and .Net 4.0 app in VS 2010). All 3 have exactly same UI and code implemented.

I see that even when I remove the hooked event handlers in my attached behavior by checking the changed data context as "NamedObject" (in the .Net 4.0 app in VS2010), my virtualised unusable items from a listbox continue to remain in the memory.

The whole exercise has made me believe that WPF could be poor in memory management esp. attached behaviors on virtualised items.

Plz enlighten me!

Vinit Sankhe.