Reputation: 1161
I am new to using Commands and was trying the CanExecute to enable and disable my buttons depending on some factors. But I am doing something wrong and cant figure it out. When loading it works fine. The CanExecuteGenerate Function gets hit, the model is null, thus returning false. Button on UI is disabled. But from ther it never hits the CanExecuteGenerate again, resulting in my button to stay disabled. Can anyone see what I am missing or doing wrong?
public class MainWindowViewModel: PropertyChangedNotification{
public RelayCommand GenerateCommand { get; set; }
public MainWindowViewModel( ) {
GenerateCommand = new RelayCommand( OnGenerateClicked, CanExecuteGenerate( ) );
Model = new MainModel( );
}
private Func<bool> CanExecuteGenerate( ) {
if( Model != null ) {
return ( ) => ( Model.Name != "" && Model.Title != "" ) ? true : false;
}
return ( ) => false;
}
public void someothermethod(){
Model.Name = "James"
Model.Title = "Doctor"
GenerateCommand.RaiseCanExecuteChanged();
}
public void OnGenerateClicked(){
//Do some other stuff
}
}
Upvotes: 0
Views: 1411
Reputation: 4016
Because your CanExecuteGenerate method returns a delegate that will be called. Try this one:
public class MainWindowViewModel: PropertyChangedNotification{
public RelayCommand GenerateCommand { get; set; }
public MainWindowViewModel( ) {
GenerateCommand = new RelayCommand( OnGenerateClicked, CanExecuteGenerate);
Model = new MainModel( );
}
private bool CanExecuteGenerate( ) {
if( Model != null )
return ( Model.Name != "" && Model.Title != "" ) ? true : false;
return false;
}
public void someothermethod(){
Model.Name = "James"
Model.Title = "Doctor"
GenerateCommand.RaiseCanExecuteChanged();
}
public void OnGenerateClicked(){
//Do some other stuff
}
}
Upvotes: 0
Reputation: 2154
When you create the RelayCommand
you always pass the method that returns false.
You should not create a separate method for the case when model is null, but to handle it in the method you are passing to the RelayCommand
.
Try using this method:
private bool CanExecuteGenerate( ) {
if( Model != null ) {
return Model.Name != "" && Model.Title != "";
}
return false;
}
And change the construction of the RelayCommand
to
GenerateCommand = new RelayCommand(OnGenerateClicked, CanExecuteGenerate);
Upvotes: 1