Little puzzled
If i have a button in a wpf window and bind it to a DelegateCommand
<Button Grid.Row="1" Content="Remove" Command="{Binding CommandDelete }" />
And in my simple viewmodel i attach
CommandDelete = new DelegateCommand<string>(OnDeleteExecute, OnDeleteCanExecute);
If the button is to be enabled when i choose an item from a list i can bind the list selecteditem to property in my viewmodel
Report selectedReport;
public Report SelectedReport
{
get { return this.selectedReport ;}
set { this.selectedReport = value;}
}
private bool OnDeleteCanExecute(string commandParameter)
{
return (this.selectedReport != null);
}
This seems fine to me so far and the only thing missing is to raise a CanExecute event for the specific button in the setter for SelectedReport
CommandDelete.RaiseCanExecuteChanged();
This works but my question is if i have 10 button do i need to call RaiseCanExecuteChanged for each and every button each time a item is selected or is there as smarter way
Usually I place my
RaiseCanExecuteChanged()in thePropertyChangedevent for that class.For example, if
DeleteCommand.CanExecuteis based on theSelectedReportproperty, I’ll hook into thePropertyChangedevent of theViewModeland raise theCanExecuteChangedevent anytimeSelectedReportchanges.This keeps all the logic in one central place and ensures the
CanExecuteChangedgets raised whenever one of the parameters changes.The other alternative is to switch from using a
DelegateCommandto aRelayCommand, which automatically raise it’sCanExecuteChangedwhen a property changes. I would assume there’s a performance difference, however have never noticed one.