wpf 为 MVVM Light ICommand 正确使用 CanExecute

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17222802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:03:10  来源:igfitidea点击:

Correctly Using CanExecute for MVVM Light ICommand

c#wpfmvvm

提问by togglebutton

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. My WPF application is in VS 2012 C# 4.5 framework.

我开始在 C# 中学习 MVVM,我想知道如何在 MVVM Light 中为 ICommand 正确使用 CanExecute 方法。我的 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. Maybe

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

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

采纳答案by KeyboardFriendly

回答by Saykor

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