是否可以将Android复选框绑定到在更改时执行命令?找不到示例。
是否可以将Android复选框绑定到在更改时执行命令?找不到示例。
标准的方法是在您的视图模型中绑定到bool类型的属性,然后在此属性的setter中执行逻辑。您的绑定将如下所示:
标准做法是简单地绑定到您视图模型中的布尔属性,并在该属性的设置器中执行逻辑。您的绑定将如下所示:
local:MvxBind="Checked IsChecked"
然而,如果你真的需要绑定到Command,你也可以绑定到Click事件:
local:MvxBind="Checked IsChecked; Click YourCommand;"
视图模型:
private bool _isChecked;
public bool IsChecked
{
get { return _isChecked; }
set
{
_isChecked = value;
RaisePropertyChanged(() => IsChecked);
}
}
public ICommand YourCommand
{
get
{
return new MvxCommand(() =>
{
var isChecked = IsChecked;
//Now you can use isChecked variable
});
}
}
请注意,您的命令参数中不会接收复选框的值,因此您仍然需要绑定到布尔属性。这种解决方案的另一个问题是,您必须依赖于一个事实,即在调用属性的setter之前将调用您的命令。public class CheckBoxChangedBinding
: MvxAndroidTargetBinding
{
private ICommand _command;
protected CheckBox View
{
get { return (CheckBox) Target; }
}
public CheckBoxChangedBinding(CheckBox view)
: base(view)
{
view.CheckedChange += CheckBoxOnCheckedChange;
}
private void CheckBoxOnCheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e)
{
if (_command == null)
return;
var checkBoxValue = e.IsChecked;
_command.Execute(checkBoxValue);
}
protected override void SetValueImpl(object target, object value)
{
_command = value as ICommand;
}
public override MvxBindingMode DefaultMode
{
get { return MvxBindingMode.OneWay; }
}
public override Type TargetType
{
get { return typeof (ICommand); }
}
protected override void Dispose(bool isDisposing)
{
if (isDisposing)
{
var view = View;
if (view != null)
{
view.CheckedChange -= CheckBoxOnCheckedChange;
}
}
base.Dispose(isDisposing);
}
}
在 Setup.cs 文件中:protected override void FillTargetFactories(IMvxTargetBindingFactoryRegistry registry)
{
base.FillTargetFactories(registry);
registry.RegisterCustomBindingFactory<CheckBox>("CheckedChanged",
checkBox => new CheckBoxChangedBinding(checkBox));
}
在你的布局中:
<CheckBox
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
local:MvxBind="CheckedChanged CheckBoxCheckedCommand" />
最后是ViewModel:
public ICommand CheckBoxCheckedCommand
{
get
{
return new MvxCommand<bool>(isChecked =>
{
var parameter = isChecked;
});
}
}