简体   繁体   中英

MVVM Light RelayCommand not working

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
    }



}

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);

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
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM