tags:

views:

145

answers:

1

Using commands is handy because WPF automatically disables the source of the command (typically a button) when the command can't be executed.

Evidently, this feature is not available to controls that are not a command source e.g. ListBox.

What is the best way to enable this feature for non command source controls. I thought of a couple of solution:

  • Wrap the ListBox with a Button and change the control template of the button so that there is no chrome.
  • Create an invisible button and bind the IsEnabled property of the ListBox to the IsEnabled property of the button
  • Create a descendant of ListBox that implement ICommandSource.

Is there a more elegant way?

+4  A: 

You can create a bool property in your code-behind (or view model) like CanSelect or CanEdit and bind the IsEnabled property of your ListBox to it. Just set the value of this new property in the CanExecute method of the corresponding command.

Julien Poulin
Thanks for the answer. Where does the CanExecute method come from though?
tom greene
I'm referring to the ICommand.CanExecute method (http://msdn.microsoft.com/en-us/library/system.windows.input.icommand.canexecute.aspx) that is used by WPF to determine if the command can be executed or not.
Julien Poulin
Got it. So who would call ICommand.CanExecute. If the command is attached to a button, WPF does the job (my point #2). Otherwise, how would this work?
tom greene
Well, I don't know if you need a Command after all, I thought you already had one and you could just change your new property from there. Maybe you could give us more details and some code about what you want to accomplish...
Julien Poulin