Home > Net >  Am I using ICommand correctly?
Am I using ICommand correctly?

Time:06-19

I have simple 2 buttons. Should I create 1 ICommand or is it ok now?

internal class MainPageViewModel : INotifyPropertyChanged
{
    public ICommand RegisterBtnClickedCommand {get; }
    public ICommand LoginBtnClickedCommand {get; }

    public MainPageViewModel()
    {
        RegisterBtnClickedCommand = new Command(RegisterButtonPressed);
        LoginBtnClickedCommand = new Command(LoginButtonPressed);
    }

    private void LoginButtonPressed()
    {
        Application.Current.MainPage.DisplayAlert("Login", "Login", "ok");
    }

    private void RegisterButtonPressed()
    {
        Application.Current.MainPage.DisplayAlert("Reg", "Reg", "ok");
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

And for example, if I had 10 buttons, then I should have 10 commands?

CodePudding user response:

And for example, if I had 10 buttons, then I should have 10 commands?

Yes.

Note that a single command might be invoked in different ways (button, menu entry, keyboard shortcut, unit test code), and that each command might have a different CanExecute logic. Thus, commands provide a convenient separation of concerns between the command itself (= your ICommand) and the way it is invoked (bindings in XAML).

If you are worried about too much boilerplate code, you can shorten your code slightly by initializing the property right at the point of declaration (rather than inside the constructor):

public ICommand RegisterBtnClickedCommand { get; } = new Command(RegisterButtonPressed);
...

CodePudding user response:

Keep two separate commands for this. "Login" and "Register" are distinct enough actions. You can reuse commands for something like deleting an item from a list and pass in parameters to identify the item, but this is not the case here.

Though I wouldn't include Btn, Button, and Pressed in their names as they should be separated from any UI ideas (imagine a link being used later on instead of a button). I'd go with LoginCommand and LoginExecute for example.

  • Related