Use Action<T1,T2> when register Method in Messenger

125 views Asked by At

I'm using mvvm pattern, and have the next situation. For example exists a method:

    void LockPressed(KeyEventArgs e)
    {
       // Code
    }

And here I register it:

    App.Messenger.Register("LockPressed", (Action<KeyEventArgs>)LockPressed);

Thath works fine. But If I need to modify method, for it to take two parameters:

    void LockPressed(KeyEventArgs e, string name)
    {
       //Code
    }

Logicaly resgister operation should look like:

    App.Messenger.Register("LockPressed", (Action<KeyEventArgs,string>)LockPressed);

But no success. I got an error:

Error CS1503 Argument 2: cannot convert from 'System.Action' to 'System.Action'

Any ideas how can I workaround it?

1

There are 1 answers

3
Jehof On

This should work:

App.Messenger.Register("LockPressed", (KeyEventArgs eventArgs)=>LockPressed(eventArgs, "name"));

or more complex

App.Messenger.Register("LockPressed", (KeyEventArgs eventArgs)=>
  {
    string name = GetName();
    LockPressed(eventArgs, name);
  });

or

Action<KeyEventArgs> lockPressedAction = (eventargs) => LockPressed(eventargs,"g");
App.Messenger.Register("LockPressed", lockPressedAction);