RelayCommands overriding the "IsEnabled" of my buttons
RelayCommands overriding the "IsEnabled" of my buttons.
Is this is a bug? Here is 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 {开发者_如何学JAVA return new RelayCommand(() => MessageBox.Show("Clear Command")); }
}
Notice I hardcoded the IsEnabled="False" in my xaml. This value is completely ignored (button always enabled).
I realize that RelayCommand have a CanExecute overload but I did want to use this as I want to do more than just have a disabled button.
That's an interesting point. You are right, the IsEnabled property gets overriden. I guess an improvement could be to ignore the IsEnabled property if the CanExecute delegate is not set in the constructor... I will consider it in a next version.
In the mean time, use the CanExecute delegate and set it to return false always.
public RelayCommand ClearCommand
{
get { return new RelayCommand(
() => MessageBox.Show("Clear Command"),
() => false); }
}
Cheers, Laurent
Here is my implementation...
1) RelayCommand class declaration could be as:
public class RelayCommand : ViewModelBase, ICommand
2) Implementation of IsEnabled property could be as follows:
public bool IsEnabled
{
get { return _isEnabled; }
set
{
if (value != _isEnabled)
{
_isEnabled = value;
OnPropertyChanged("IsEnabled");
}
}
}
3) Lastly you need to bind the IsEnabled property in xaml as follows:
IsEnabled="{Binding Path=SearchCommand.IsEnabled}"
精彩评论