views:

220

answers:

1

Hi
I have a simple WPF with a menu, a toolbar and a ListView in a GridView. the menu and toolbar actions are bound to commands. I have that defines when commands should be executed ("CanExecute"). Some commands, such as "Create New Item" should always be executed, so they are bound to a "e.CanExecute = true;" function.

However, when the user selects all items in the list using Ctrl-A, and then press Delete, my application runs a BackgroundWorker that deletes the items from the server and then sets the ItemsSource of the list view to the new data collection, which is empty.

This sometimes causes all commands in the menu and toolbar to be disabled. Note that their keyboard shortcuts still work, but the actions are disabled in the menu and toolbar.

This doesn't always happen, and I failed to find a rule to when it does happen.

Did anyone run into a similar behavior or has any idea what might cause it?

Thanks, Shmulik

+1  A: 

Hi Splintor,

Without code it may be hard. It looks like CanExecute() is not called. Set breakpoint in it and check. I assume you are using RoutedCommands. If yes, the problem may appear because MenuItem.CommandTarget is not set, and WPF tries to find CommandBindings somewhere up the tree, beyond your actual command bindings. If this is the case, set CommandTarget to proper value. Also you may want to call CommandManager.InvalidateRequerySuggested() and see what happens.

Anvaka
Indeed, I didn't set MenuItem.CommandTarget for any of my MenuItems (I didn't know about this property). When the problem occurs, I assume the focus is on a control that can't handle these commands. However, I fail to recreate the problem now (as I said, it intermitent). What should I set the MenuItem.CommandTarget to be for commands like ApplicationCommands.New?
splintor
You can leave it. Just make sure there is a command binding for this command somewhere up enough in the visual tree (e.g. in the main window). So whenever CanExecute is requested WPF can find your bindings and handler...
Anvaka