如何通过单击按钮更改布尔属性?

问题描述 投票:0回答:1

我正在使用Button更改我的IsSelected属性。我正在使用MVVM LightViewModelBase引发PropertyChanged事件。

模型

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);
    }
}

查看

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

如果我使用ToggleButtonIschecked属性,则这组代码可以成功工作。该代码对按钮的作用是EXCEPT。我认为我错过了一些东西。

c# mvvm mvvm-light
1个回答
0
投票

[您的ICommand实现是错误的,@ Fildor在链接this question的评论中也曾指出,这些帮助我提出了这个答案。

模型中,您需要将RelayCommandViewButton绑定。

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)
}

然后绑定此RelayCommandIsSelectedCommand,而不是直接将您的IsSelected绑定到ViewButton中。

<Button Command="{Binding IsSelectedCommand, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"> Click </Button>
© www.soinside.com 2019 - 2024. All rights reserved.