简体   繁体   English

正确使用CanExecute用于MVVM Light ICommand

[英]Correctly Using CanExecute for MVVM Light ICommand

I am starting to learn MVVM in C# and I was wondering how to correctly use the CanExecute method for an ICommand in MVVM Light. 我开始学习C#中的MVVM,并且想知道如何为MVVM Light中的ICommand正确使用CanExecute方法。 My WPF application is in VS 2012 C# 4.5 framework. 我的WPF应用程序在VS 2012 C#4.5框架中。

How to correctly implement CanExecute? 如何正确实现CanExecute?

I have just been returning true, but I know there is a proper way to handle it. 我刚刚返回true,但是我知道有正确的方法来处理它。 Maybe 也许

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

Here is some of the sample code. 这是一些示例代码。

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

Declare command 声明命令

public ICommand SaveCommand { get; set; }

In constructor: 在构造函数中:

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

Methods: 方法:

private bool CanExecuteSaveCommand()
    {
        return SelectedOrder.ContactName != null;
    }
private void ExecuteSaveCommand()
    {
        Save();
    }

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

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

http://www.c-sharpcorner.com/UploadFile/1a81c5/a-simple-wpf-application-implementing-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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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