簡體   English   中英

MVVM Light RelayCommand不起作用

[英]MVVM Light RelayCommand not working

我是使用Commands的新手,並根據某些因素嘗試使用CanExecute啟用和禁用我的按鈕。 但是我做錯了事,無法解決。 加載時工作正常。 CanExecuteGenerate函數被命中,模型為null,因此返回false。 UI上的按鈕已禁用。 但是從那里開始,它再也不會擊中CanExecuteGenerate,導致我的按鈕保持禁用狀態。 誰能看到我的缺失或做錯了什么?

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
    }



}

創建RelayCommand您總是傳遞返回false的方法。

對於model為null的情況,您不應為該情況創建單獨的方法,而應在傳遞給RelayCommand的方法中對其進行RelayCommand

嘗試使用此方法:

private bool CanExecuteGenerate( ) {
    if( Model != null ) {
        return Model.Name != "" && Model.Title != "";
    }

    return false;
} 

並將RelayCommand的構造更改為

GenerateCommand = new RelayCommand(OnGenerateClicked, CanExecuteGenerate);

因為您的CanExecuteGenerate方法返回了將被調用的委托。 試試這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM