Command binding allows you to separate common application commands (and their invocation) from where they are handled. You can write your classes to handle specific commands, or not, and even indicate if those commands can be executed. The problem, much like the others we've seen, occurs when these bindings leave unwanted strong references lying around.
Say I'm setting up some code within a child window to handle when Cut is executed within the parent mainWindow. I first create a CommandBinding, and then simply add it to the parent windows CommandBindings collection:
The good news is that the .NET framework now takes care of freeing objects for you, and is also ultra-cautious. It works out whether it thinks a particular object is going to be needed while your program runs, and it will only release that object if it can completely guarantee that that object is not going to be needed again.
CommandBinding cutCmdBinding = new CommandBinding
(ApplicationCommands.Cut, OnMyCutHandler, OnCanICut);
void OnMyCutHandler (object target, ExecutedRoutedEventArgs e)
MessageBox.Show("You attempted to CUT");
void OnCanICut (object sender, CanExecuteRoutedEventArgs e)
e.CanExecute = true;
This code leaks because we are leaving a strong reference in the mainWindow.main.CommandBindings object pointing to the child. As a result, even when the child closes, it will still remain in memory.