15

When should I use the Command and when to use the Click event?

F.e. if I have a Button in my UWP app what should I use?

3
  • 5
    command is binded with your viewmodel, while click event is written in code behind Sep 18, 2016 at 9:39
  • 6
    The other bonus with command is that it has CanExecute so your UI can grey out the button when its not possible to perform the action. For best practise you should use the ICommand interface it makes your code much cleaner and easier to maintain in the long run, but if you are only going to have 1 button for a simple app then there's no real problem in just using the click event.
    – mbrdev
    Sep 18, 2016 at 9:51
  • 4
    Another advantage of Command is that the same command can be bound to more than one UI element (e.g. you can bind the same command to a menu item and to a toolbar button).
    – Joe
    Apr 18, 2017 at 7:49

1 Answer 1

33

When should I use the Command and when to use the Click event?

Yours is a broad question and I would simply answer with: "It depends". Because:

  • The Command implements the ICommand interface and this means more code to add to your application but usually this won't change. Instead, the event handler doesn't require any interface implementation.
  • For every command you want, you have to provide the code that will handle the click and the CanExecute logic, to say when the command can execute. This is not required in a simple event handler (like MyButton_Click). This means that, using a Command, you will have more control over the elements of your UI (the button won't execute anything if CanExecute is false).
  • When you want to add a Command, you will bind it to your DataContext (the ViewModel, if you implement the MVVM pattern). Instead, when you add a simple event handler (like MyButton_Click), the code will be placed in your code-behind that is the logic behind your main window. In my opinion, this is best, as you'll have everything you need to modify in just one place (the ViewModel) instead of logic scattered everywhere in your project.

At the end of the day, it's up to you to use whatever suits you best, considering also the requirements you have been given (like: "Don't use event handlers" or "The Command is too advanced, let's just use something simple", etc.) and/or other constraints in your project.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.