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 aButton
and change theControlTemplate
of the button so that there is no chrome. - Create an invisible
Button
and bind theIsEnabled
property of theListBox
to theIsEnabled
property of theButton
- Create a descendant of
ListBox
that implementsICommandSource
.
Is there a more elegant way?
Best Answer
You can create a bool property in your code-behind (or view model) like
CanSelect
orCanEdit
and bind theIsEnabled
property of yourListBox
to it. Just set the value of this new property in theCanExecute
method of the corresponding command.