Mvvmcross bind to Visibility with autolayout and f

2019-08-27 12:29发布

问题:

Currently binding to "Visibility" sets Hidden=true. How would you create a generic Visibility binding which also changes a constraint: sets the view height to 0 ?

回答1:

For a tutorial on creating bindings, see the N=28 video on http://mvvmcross.blogspot.com/

To replace the existing visibility binding, simply create your own class based on https://github.com/MvvmCross/MvvmCross/blob/v3.1/Cirrious/Cirrious.MvvmCross.Binding.Touch/Target/MvxUIViewVisibleTargetBinding.cs

public class MyUIViewVisibleTargetBinding : MvxBaseUIViewVisibleTargetBinding
{
    public MyUIViewVisibleTargetBinding(UIView target)
        : base(target)
    {
    }

    protected override void SetValueImpl(object target, object value)
    {
        var view = View;
        if (view == null)
            return;

        var visible = value.ConvertToBoolean();
        // your code here
        // - in place of or in addition to:
        // view.Hidden = !visible;
    }
}

And register this as the last step in Setup using:

protected override void InitializeLastChance()
{
     base.InitializeLastChance();

     var registry = Mvx.Resolve<IMvxTargetBindingFactoryRegistry>();
     registry.RegisterCustomBindingFactory<UIView>("Visible",
                                                    view =>
                                                    new MyUIViewVisibleTargetBinding(view));

}

For more on replacing existing bindings, see MVVMCross Binding decimal to UITextField removes decimal point


Note that if you want to replace all Visible bindings, then you might want to replace all of Visible, Visibility and Hidden - see registrations in https://github.com/MvvmCross/MvvmCross/blob/v3.1/Cirrious/Cirrious.MvvmCross.Binding.Touch/MvxTouchBindingBuilder.cs#L42