Question

I thought I'd got my head around delegates, in that it creates a reference to a method and then can be referenced by 'external' code (another dll/project).

Now I'm using MVVM and I see this thing called RelayCommand which appears as if it is passing a method as a parameter in the same way a delegate is passed. How is this possible?

The code I'm looking at is

        public RelayCommand AddUserCommand { get; set; }

        public ViewModelMain()
        {
            this.AddUserCommand = new RelayCommand(AddUser, null);
        }

        void AddUser(object parameter)
        {
            //logic
        }

and the RelayCommand object is

public class RelayCommand : ICommand
{
    public RelayCommand(Action<object> execute, Predicate<object> canExecute)
    {
         //logic
    }
}

So since there is no delegate can I assume some trickery is occurring with the Action<> object?

Était-ce utile?

La solution

Action<object> is a delegate. When you write:

new RelayCommand(AddUser, null)

the compiler rewites it as:

new RelayCommand(new Action<object>(AddUser), null)

Which creates the reference to a method, as you're expecting.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top