How do I disable a button bound to a current item's ICommand when there is no current item?
.net, binding, c#, mvvm, wpf
Solution
I'd do it similar to akjoshi, only I'd use a normal Trigger instead of a DataTrigger, and I'd check on Button.Command to be null. Since it always makes sense to disable a Button that has no Command (especially in MVVM, where there are no click eventhandlers), it would also be a good idea to include this trigger into a default style for Buttons, in order to have this behaviour on all Buttons across the application... I don't see a reason to use a dummy command.
Problem
Say you have a button whose `command` property is bound to some `ICommand` of the current item of some collection. When the collection is `null`, the button remains enabled and clicking it seems to be a no-op. I want instead that the button remains disabled. I figured out the following to keep buttons disabled whenever the collection is null. It however seems a bit too convoluted for something that could perhaps be accomplished in a more natural, simpler, and more MVVM like. Hence the question: is there a simpler way to keep that button disabled, ideally where no code-behind is used? .xaml: ``` <Button Content="Do something" > <Button.Command> <PriorityBinding> <Binding Path="Items/DoSomethingCmd" /> <Binding Path="DisabledCmd" /> </PriorityBinding> </Button.Command> </Button> ``` .cs: ``` public class ViewModel : NotificationObject { ObservableCollection<Foo> _items; public DelegateCommand DisabledCmd { get; private set; } public ObservableCollection<Foo> Items { get { return _items; } set { _items = value; RaisePropertyChanged("Items"); } } public ViewModel() { DisabledCmd = new DelegateCommand(DoNothing, CantDoAnything); } void DoNothing() { } bool CantDoAnything() { return false; } } ``` Edit: A couple of notes: - I am aware that I can use lambda expressions, but in this example code I do not. - I know what a predicate is. - I don't see how doing something with `DoSomethingCmd.CanExecute` will do anything to help as there is no `DoSomethingCmd` to access while there is no current item. - So I'll re-center my question: How can I avoid using the `DisabledCmd`? I am not interested in moving up the `DoSomethingCmd` as it is not what I am looking for. I wouldn't be asking this question otherwise. Another edit: So I basically adopted this answer as a solution: WPF/MVVM: Disable a Button's state when the ViewModel behind the UserControl is not yet Initialized? It is, I believe, exactly what hbarck proposes.