2

我开始在 C# 中学习 MVVM,我想知道如何在 MVVM Light 中为 ICommand 正确使用 CanExecute 方法。我的 WPF 应用程序位于 VS 2012 C# 4.5 框架中。

如何正确实现 CanExecute?

我刚刚回归真实,但我知道有一种正确的方法来处理它。也许

if(parameter != null)
{
   return true;
}

这是一些示例代码。

    private RelayCommand sendCommand;
    public ICommand SendCommand
    {
        get
        {
            if (sendCommand == null)
                sendCommand = new RelayCommand(p => SendStuffMethod(p), p => CanSendStuff(p));
            return sendCommand;
        }
    }


    private bool CanSendStuff(object parameter)
    {
        return true;
    } 

    private void SendStuffMethod(object parameter)
    {
       string[] samples = (string[])parameter; 

       foreach(var sample in samples)
       {
          //Execute Stuff
       }   
    }
4

2 回答 2

3

声明命令

public ICommand SaveCommand { get; set; }

在构造函数中:

public SelectedOrderViewModel()
    {
        SaveCommand = new RelayCommand(ExecuteSaveCommand, CanExecuteSaveCommand);
    }

方法:

private bool CanExecuteSaveCommand()
    {
        return SelectedOrder.ContactName != null;
    }
private void ExecuteSaveCommand()
    {
        Save();
    }
于 2014-08-22T18:45:05.570 回答
-2

http://www.identitymine.com/forward/2009/09/using-relaycommands-in-silverlight-and-wpf/

http://matthamilton.net/commandbindings-with-mvvm

http://www.c-sharpcorner.com/UploadFile/1a81c5/a-simple-wpf-application-implementing-mvvm/

bool CanSendStuff(object parameter);
    //
    // Summary:
    //     Defines the method to be called when the command is invoked.
    //
    // Parameters:
    //   parameter:
    //     Data used by the command. If the command does not require data to be passed,
    //     this object can be set to null.
    void Execute(object parameter);
于 2013-06-28T15:32:46.860 回答