I’ve created an ‘attached behaviour’ in my WPF application which lets me handle the Enter keypress and move to the next control. I call it EnterKeyTraversal.IsEnabled, and you can see the code on my blog here.
My main concern now is that I may have a memory leak, since I’m handling the PreviewKeyDown event on UIElements and never explicitly ‘unhook’ the event.
What’s the best approach to prevent this leak (if indeed there is one)? Should I keep a list of the elements I’m managing, and unhook the PreviewKeyDown event in the Application.Exit event? Has anyone had success with attached behaviours in their own WPF applications and come up with an elegant memory-management solution?
I do not agree DannySmurf
Some WPF layout objects can clog up your memory and make your application really slow when they are not garbage collected. So I find the choice of words to be correct, you are leaking memory to objects you no longer use. You expect the items to be garbage collected, but they aren’t, because there is a reference somewhere (in this case in the from an event handler).
Now for a real answer 🙂
I advise you to read this WPF Performance article on MSDN
They advise you to look into the Weak Event pattern
Another solution would be to remove the event handlers when you are done with an object. But I know that with Attached Properties that point might not always be clear..
Hope this helps!