简体   繁体   中英

Implementing a Non-Static Handler for ICommand

Using what I believe to be the ICommand pattern for Xamarin Forms I've implemented this

        private Command _onButtonTapCommand = new Command(onButtonTapCommand);
        public ICommand OnButtonTapCommand { get { return _onButtonTapCommand; } }
        private static async void onButtonTapCommand(object obj) {}

This all works, but I'd prefer not to have the handler method be static. Removing static generates the compile error that you'd expect: the field initializer can't reference the non-static method. Is there a different pattern that I've missed?

I think the solution is to simply initialize the Command in the constructor.

private Command _onButtonTapCommand;
        public ICommand OnButtonTapCommand { get { return _onButtonTapCommand; } }
        private async void onButtonTapCommand(object obj);

public YourClass()
{
    _onButtonTapCommand = new Command(onButtonTapCommand();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM