Alerter
Alerter

Reputation: 249

Command Binding - CanExecute() is getting called even after the window is closed in WPF app

I've a tool bar which has its own view model. I've used command binding handle the clicks in the view model. I've used codeplex's command class that comes up with the toolkit. When I close the window and open another window in the same application, I see my CanExecute() of the previously closed window's method getting called. I've got it confirmed by using CommandManager.InvalidateRequerySuggested() that the CommandManager is still holding the reference!! CommandManager is supposed hold Weak reference but for some reason it is not releasing the delegates at all.

What have I done wrong here? How can I overcome this issue?

Upvotes: 6

Views: 1274

Answers (2)

Danwizard208
Danwizard208

Reputation: 195

As an addendum to surfen's answer, I ended up solving this issue by adding the line

CommandBindings.Clear()

in my Window's Closed event. This should work if your command bindings are all made on the Window, or else you should call it on whatever control owns the CommandBindings.

Upvotes: 1

surfen
surfen

Reputation: 4692

The reason why this is happening is that CommandManager has no clue that it should stop firing CanExecute until the handler gets garbage collected.

I had the same issue and I've solved it by setting DataContext of the window to null just after closing the window. It works fine assuming that the commands are bound to ViewModel (removing he DataContext unregisters the canExecute event handlers).

Upvotes: 6

Related Questions