You can specify a condition under which a command should be active. Add a "When" clause to MakeCommand.

The user should be able to click the log on button only when they have entered a user name. Add that condition to the LogOn command in MachineViewModel.
public ICommand LogOn
{
    get
    {
        return MakeCommand
            .When(() => !string.IsNullOrEmpty(_navigation.UserName))
            .Do(() => _machine.LogOnUser(_navigation.UserName));
    }
}
Add a test to MachineViewModelTest to verify that the command is not active when there is no user name.
[TestMethod]
public void LogOnIsInitiallyDisabled()
{
    Assert.IsFalse(_viewModel.LogOn.CanExecute(null));
}
Add another test to verify that it is active after the user name is entered.
[TestMethod]
public void LogOnIsEnabledAfterUserNameIsEntered()
{
    _viewModel.UserName = "alan1";
    Assert.IsTrue(_viewModel.LogOn.CanExecute(null));
}
After the user has logged on, they can't hit the log on button again. Write a failing test for this feature.
[TestMethod]
public void LogOnIsDisabledAfterUserLogsOn()
{
    _viewModel.UserName = "alan1";
    _viewModel.LogOn.Execute(null);

    Assert.IsFalse(_viewModel.LogOn.CanExecute(null));
}
Then add a condition to the When clause to make it pass.
public ICommand LogOn
{
    get
    {
        return MakeCommand
            .When(() => !string.IsNullOrEmpty(_navigation.UserName)
                && !_machine.LogOns.Any())
            .Do(() => _machine.LogOnUser(_navigation.UserName));
    }
}
Command activation is expressed as a boolean condition inside of a When clause. When the expression is true, the command can be executed. When it is false, it cannot.

Next: Lesson 2d: Data binding

Last edited May 15, 2011 at 4:41 AM by MichaelLPerry1971, version 3

Comments

No comments yet.