你能做的就是把这个问题的解决分为几个层次:
首先,为复选框创建一个可绑定属性,并将其命名为“Checked”。
我已经为其编写了一个片段,但并未真正编译它,因此如果它不起作用,您可能需要修改它
public static readonly BindableProperty IsCheckedProperty =
BindableProperty.Create<CheckBox, bool> (w => w.IsChecked, false);
public bool IsChecked{
get { return GetValue (FooProperty); }
set { SetValue (FooProperty, value); }
}
其次,在视图模型中创建一个具有更改通知的 bool 属性
private bool _isChecked;
public bool IsChecked
{
get
{
return _isChecked;
}
set
{
_isChecked = value;
RaisePropertyChanged("IsChecked");
}
}
第三,将复选框“isChecked”的可绑定属性绑定到 xaml 中视图模型中的属性:
<StackLayout>
<Checkbox IsChecked = "{Binding IsChecked}"/>
</StackLayout>
第四,使用 MVVM 的 Xaml 中的按钮绑定到命令。在这些命令中,有一个 bool 属性代表“CanExecute”,它基本上启用或禁用按钮。因此,您在 Xaml 中要做的就是将按钮的命令绑定到视图模型中的命令(我们称之为 ClickCommand)。而ClickCommand的CanExecute实际上只是一个返回“IsChecked”值的方法。
这将使我们修改“IsChecked”属性的设置器,因此每次更改时都应通知命令检查 CanExecute 属性。
所以最终的代码会是这样的
public TermsAndConditionsViewModel()
{
NextCommand = new Command(ExecuteNextCommand,CanExecuteNextCommand);
OnCheckBoxTapChanged = new Command(CheckBoxTapped);
}
private bool _isChecked;
public bool IsChecked
{
get { return _isChecked;}
set
{
_isChecked = value;
NextCommand.ChangeCanExecute(); //this will actually notify the command to enable/disable
RaisePropertyChanged("IsChecked");
}
}
public Command NextCommand {get;set;} // this type is available in Xamarin.Forms library
private bool CanExecuteNextCommand()
{
return IsChecked;
}
private void ExecuteNextCommand()
{
// your execution when the button is pressed
}
Xaml 会像
<StackLayout>
<Checkbox IsChecked = "{Binding IsChecked}"/>
<Button Text= "Next" Command = "{Binding NextCommand}"/>
</StackLayout>