【问题标题】:Correctly Using CanExecute for MVVM Light ICommand为 MVVM Light ICommand 正确使用 CanExecute
【发布时间】:2013-06-20 20:05:42
【问题描述】:

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

如何正确实现CanExecute?

我刚刚返回 true,但我知道有适当的方法来处理它。也许

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

【问题讨论】:

  • POLS:如果没有设置命令,Getter 应该返回 null,分配任何东西不是 getter 的工作......也就是说我在 viewmodel 中创建了一个 CanDoSomething(object cmdState) 方法并分配该方法到命令的CanExecute 操作。
  • ...这基本上就是您似乎正在做的事情。只需使用 viewmodel 的属性来确定返回值 :)
  • 我不确定我是否听懂了你的问题。 “如何为RelayCommand 正确实施CanExecute()?”。这肯定取决于您的用例。如果你想让函数返回true,如果你想允许绑定到它的视图能够执行它,否则让它返回false。使用您需要导致该方法返回bool 的任何逻辑来指示绑定的RelayCommand 是否可用。如果您有一个始终返回 true 的命令,您可以在创建时忽略 RelayCommand 的构造函数的第二个参数。像new RelayCommand(ExecuteCommand); 这样的东西会做

标签: c# wpf mvvm


【解决方案1】:

声明命令

public ICommand SaveCommand { get; set; }

在构造函数中:

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

方法:

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

【讨论】:

    【解决方案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-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-26
      • 1970-01-01
      • 1970-01-01
      • 2013-01-01
      相关资源
      最近更新 更多