Search code examples
buttonxamarin.formscommandmvvmcross

What's the best practice to disable a button in Xamarin.Forms, MvvmCross, when using Command?


I have some troubles in disabling a Button's Command in a Xamarin.Forms MvvmCross project. IsEnabled doesn't seem to work properly, even if using the CanExecute property.

On the yaml file of the page:

<Button Text="DoSomething" Command="{Binding DoSomethingCommand}" IsEnabled="{Binding DoSomethingIsEnabled}"/>

On the view model:

public IMvxCommand DoSomethingCommand => new MvxCommand(() => System.Diagnostics.Debug.WriteLine("Is enabled!"));

or 

public IMvxCommand DeviceButtonCommand => new MvxCommand(() => System.Diagnostics.Debug.WriteLine("Is enabled!"), () => DoSomethingIsEnabled);

I read some posts about it but I haven't solved the problem yet, no idea?


Solution

  • I think you need to call a method on the command when you change the property specified in the CanExecute delegate. Something like ChangeCanExecute() for XF. And I don't remember the name for mvvmcross :)

    EDITED: it's RaiseCanExecuteChanged for MvvmCross.

    private bool _doSomethingIsEnabled;
    public bool DoSomethingIsEnabled
    {
        get => _doSomethingIsEnabled;
        set
        {
            _doSomethingIsEnabled = value;
            DoSomethingCommand.ChangeCanExecute();
        }
    }