RelayCommands overriding the "IsEnabled" of my buttons
RelayCommands overrides the "IsEnabled" of my buttons.
This is mistake? Here is the xaml from my View and code from my ViewModel
<Button Grid.Column="0" Content="Clear" IsEnabled="False" cmd:ButtonBaseExtensions.Command="{Binding ClearCommand}" />
public RelayCommand ClearCommand
{
get { return new RelayCommand(() => MessageBox.Show("Clear Command")); }
}
Please note that I have hardcoded IsEnabled = "False" in my xaml. This value is completely ignored (the button is always on).
I understand that the RelayCommand has an overload of CanExecute, but I really wanted to use that as I want to do more than just disable the button.
a source to share
This is an interesting point. You are right, the IsEnabled property is being overloaded. I think an improvement might be to ignore the IsEnabled property if the CanExecute delegate is not set in the constructor ... I'll cover it in the next version.
In the meantime, use the CanExecute delegate and set it to always false.
public RelayCommand ClearCommand
{
get { return new RelayCommand(
() => MessageBox.Show("Clear Command"),
() => false); }
}
Cheers, Laurent
a source to share
Here is my implementation ...
1) The declaration of the RelayCommand class can be as follows:
public class RelayCommand: ViewModelBase, ICommand
2) The implementation of the IsEnabled property could be as follows:
public bool IsEnabled
{
get { return _isEnabled; }
set
{
if (value != _isEnabled)
{
_isEnabled = value;
OnPropertyChanged("IsEnabled");
}
}
}
3) Finally, you need to bind the IsEnabled property in the xaml like this:
IsEnabled = "{Binding Path = SearchCommand.IsEnabled}"
a source to share