views:

196

answers:

2

I have a related question here where i have a user control with a command binding. The user control has being removed from the visual tree, yet the canExecute is still firing. My understanding of the Commanding model was that it bubbles and tunnels like routed events. So how can the CanExecute fire once the element with the command binding attached is no longer in the visual tree?

A: 

My Guess is that there is an instance of the command registered with the commandmanager. Commands can be executed from many different sources not just UI for example shortcut keys.

Try calling CommandManager.InvalidateRequerySuggested(); and add a break point in your canexecute method to confirm that this is the case.

Hope this helps.

Steve Psaltis
A: 

IMO, CommandBindings are really poorly implemented in WPF. You have to work around the fact that the system keeps a WeakReference to your control if it has a CommandBinding, even when the control is closed.

You will see lots of examples online on how to set up a CommandBinding in XAML code. The problem is all these examples are going to introduce performance problems into any app where they are pasted. The CommandBindings never go away properly on their own. At least, not for a long time.

The solution is to:

A) Do not set up CommandBindings in XAML. You have to use the code behind. Suggest using the Constructor after you have called InitializeComponent(). Use this.CommandBindings.Add() to add the CommandBindings with code.

B) handle the Closed() event of your Window or Control and call this.CommandBindings.Clear().

This is the only way I have been able to reliably get the CommandBindings to quit firing. I think this is a ridiculous way for this feature to have been implemented by Microsoft. The fact that so many online examples teach you to declare CommandBindings in XAML just exacerbates the problem.

HugeHugh
this means that you should never declare a command binding on a user control (as you dont have the closed event) and this could lead to memory issues.
Aran Mulholland