MvvmCross 复选框绑定到命令 android xml

MvvmCross Checkbox bind to command android xml

是否可以绑定 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
        });
    }
}

请注意,您不会在命令参数中收到复选框的值,因此无论如何您都需要绑定到 bool 属性。此解决方案的另一个问题是您必须依赖一个事实,即您的 属性 的 setter 将在您的命令之前被调用。

如果您真的需要使用带有 bool 参数的命令,那么您绝对可以这样做。 MvvmCross 框架最棒的一点是你可以随时扩展它的功能。在您的情况下,您需要为 CheckBox 实现自定义绑定。好的起点可能在这里:http://slodge.blogspot.cz/2013/06/n28-custom-bindings-n1-days-of-mvvmcross.html

编辑: 为了展示它的简单性,我尝试了使用 bool 参数实现简单的命令绑定。 (没有 CanExecute 检查)。如果有人感兴趣,这里是代码。
绑定 class:

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