Is Josh Smith’s implementation of the RelayCommand flawed?

I’ve found the answer in Josh’s comment on his “Understanding Routed Commands” article:

[…] you have to use the WeakEvent pattern in your CanExecuteChanged
event. This is because visual elements will hook that event, and since
the command object might never be garbage collected until the app
shuts down, there is a very real potential for a memory leak. […]

The argument seems to be that CanExecuteChanged implementors must only hold weakly to the registered handlers, since WPF Visuals are to stupid to unhook themselves. This is most easily implemented by delegating to the CommandManager, who already does this. Presumably for the same reason.

Leave a Comment