Relaycommand and parameterless execute method

后端 未结 1 673
自闭症患者
自闭症患者 2021-02-09 16:08

I\'m currently learning WPF and MVVM, I think I get most of it and how it works but I\'ve come across something on using the RelayCommand (or DelegateCommand) that I don\'t unde

1条回答
  •  难免孤独
    2021-02-09 16:32

    The constructor parameter is a delegate that has the following signature:

    void MethodName(T parameter)
    

    where parameter is of type T (in the case of the RelayCommand this will be of type system.Object.

    This code:

    param => this.UpdateTextContentCommand_Execute()
    

    is a lambda expression that essentially expands to this:

    void AnonymousMethod(object param)
    {
        this.UpdateTextContentCommand_Execute();
    }
    

    So in this case you are passing in a parameter (param) you are just not using it. If you understand this then you should now realise why your other examples behave the way they do.

    Example 1

    if (updateTextContentCommand == null)
    {
        updateTextContentCommand = new RelayCommand(
            this.UpdateTextContentCommand_Execute());
    }
    

    Here you are calling the method which returns void. The constructor is expecting something that matches the Action delegate hence the error.

    Example 2

    If you then remove the brackets like this:

    if (updateTextContentCommand == null)
    {
        updateTextContentCommand = new RelayCommand(
            this.UpdateTextContentCommand_Execute);
    }
    

    Think of this as being a bit like subscribing to an event:

    myObject.myevent += new Action(this.UpdateTextContentCommand_Execute);
    
    
    

    which can be shortened to:

    myObject.myevent += this.UpdateTextContentCommand_Execute;
    

    So the constructor accepts any method that has a signature that matches the Action delegates signature i.e.

    void UpdateTextContentCommand_Execute(object parameter)
    

    Your method has the following signature:

    void UpdateTextContentCommand_Execute()
    

    As you can see the signatures don't match so the compiler complains.

    When you update your UpdateTextContentCommand_Execute method to accept an object parameter it's signature now matches which is why it now works.

    0 讨论(0)
    提交回复
    热议问题