Search code examples
c#mvvmmvvm-light

How to change bool property using button click?


I am using a Button to change my IsSelected property. I am using MVVM Light's ViewModelBase to raise PropertyChanged event.

Model

private bool _isSelected = true;

public bool IsSelected
{
    get
    {
        return _isSelected;
    }
    set
    {
        Set(IsSelected, ref _isSelected, value);
        Messenger.Default.Send(Message.message);
    }
}

//ICommand
public const string isSelectedCommandPropertyName = "isSelectedCommand";

private ICommand _isSelectedCommand;

public ICommand isSelectedCommand
{
    get
    {
        IsSelected = !IsSelected;
        return null;
    }
    set
    {
        Set(isSelectedCommandPropertyName, ref _isSelectedCommand, value);
        Messenger.Default.Send(Message.message);
    }
}

View

<Button Command="{Binding IsSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"> Click </Button>

This set of codes works successfully if I use ToggleButton's Ischecked property. This code is working EXCEPT for the button. I think there's something I missed.


Solution

  • Your ICommand implementation is wrong, it is also stated by @Fildor in the comments who linked this question that helped me to come up with this answer.

    In the Model, you need the RelayCommand to be binded with the View's Button.

    private RelayCommand IsSelectedCommand {get; set;}
    
    // then your void isSelected function, this is the command to be called if button is clicked
    public void isSelectedCommand()
    {
        IsSelected = !IsSelected;
    }
    
    public your_model()
    {
        this.IsSelectedCommand = new RelayCommand(this.isSelectedCommand)
    }
    

    Then bind this RelayCommand's IsSelectedCommand instead of binding directly your IsSelected in your Button in your View.

    <Button Command="{Binding IsSelectedCommand, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"> Click </Button>