Wpf – Disabling controls based on WPF command/command bindings

commandbindingwpf

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 solutions:

  • Wrap the ListBox with a Button and change the ControlTemplate 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 implements ICommandSource.

Is there a more elegant way?

Best Answer

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.

Related Topic