简体   繁体   English

我正确使用 ICommand 吗?

[英]Am I using ICommand correctly?

I have simple 2 buttons.我有简单的 2 个按钮。 Should I create 1 ICommand or is it ok now?我应该创建 1 个ICommand还是现在可以?

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?例如,如果我有 10 个按钮,那么我应该有 10 个命令吗?

And for example, if I had 10 buttons, then I should have 10 commands?例如,如果我有 10 个按钮,那么我应该有 10 个命令吗?

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.请注意,单个命令可能会以不同的方式调用(按钮、菜单项、键盘快捷键、单元测试代码),并且每个命令可能具有不同的CanExecute逻辑。 Thus, commands provide a convenient separation of concerns between the command itself (= your ICommand) and the way it is invoked (bindings in XAML).因此,命令在命令本身(=您的 ICommand)和调用它的方式(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);
...

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).虽然我不会在它们的名称中包含BtnButtonPressed ,因为它们应该与任何 UI 想法分开(想象稍后使用链接而不是按钮)。 I'd go with LoginCommand and LoginExecute for example.例如,我会使用LoginCommandLoginExecute

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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