Setting a Command property with CanExecute in the ViewModel

JonAlzaJonAlza ESMember ✭✭

I have a question about the way to setting a Command in the ViewModel. I have a XAML page with some Entry views and one Button. I want the Button enabled only if all fields are filled, so I decided to use commands. I found two ways to implement the command:

First:

private Command myCommand
public Command MyCommand
{
    get
    {
        return this.myCommand =
            new Command(async () => await this.ExecuteMyCommand(), () => this.CanExecuteMyCommand());
    }
}

Second:

private Command myCommand
public Command MyCommand
{
    get
    {
        return this.myCommand = this.myCommand??
            new Command(async () => await this.ExecuteMyCommand(), () => this.CanExecuteMyCommand());
    }
}

If I use the first solution CanExecuteMyCommand method is executed only one time when the page is loaded. If I use the second the CanExecuteMyCommand is executed each time a field changes, this is what I need.

But I don't understand why the first doesn't work as I expected. Which is the difference between these two examples?

Best Answer

Answers

  • JonAlzaJonAlza ESMember ✭✭

    Thank you @ClintStLaurent, now I understand better what I'm doing.

Sign In or Register to comment.