如何使用按钮单击更改 bool 属性?
How to change bool property using button click?
我正在使用 Button
来更改我的 IsSelected
属性。我正在使用 MVVM Light 的 ViewModelBase
引发 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>
如果我使用 ToggleButton
的 Ischecked
属性,这组代码可以成功运行。此代码对按钮有效 EXCEPT。我想我错过了什么。
您的 ICommand
实现是错误的,@Fildor 在链接 this question 的评论中也指出了这一点,这帮助我得出了这个答案。
在模型中,您需要RelayCommand
与View
的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)
}
然后绑定此 RelayCommand
的 IsSelectedCommand
而不是直接绑定您的 IsSelected
在您的 Button
在您的 View .
<Button Command="{Binding IsSelectedCommand, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"> Click </Button>
我正在使用 Button
来更改我的 IsSelected
属性。我正在使用 MVVM Light 的 ViewModelBase
引发 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>
如果我使用 ToggleButton
的 Ischecked
属性,这组代码可以成功运行。此代码对按钮有效 EXCEPT。我想我错过了什么。
您的 ICommand
实现是错误的,@Fildor 在链接 this question 的评论中也指出了这一点,这帮助我得出了这个答案。
在模型中,您需要RelayCommand
与View
的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)
}
然后绑定此 RelayCommand
的 IsSelectedCommand
而不是直接绑定您的 IsSelected
在您的 Button
在您的 View .
<Button Command="{Binding IsSelectedCommand, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"> Click </Button>