How to bind to View's layout_weight in MvvmCro

2019-03-01 18:36发布

问题:

What is the easiest way to bind to View's (or any other Android control) weight? Because this property doesn't have a setter, I tried custom binding, but id doesn't seem to work:

public class ViewWeightCustomBinding : MvxAndroidTargetBinding
{
    public ViewWeightCustomBinding(object target) : base(target)
    {
    }

    public override Type TargetType
    {
        get { return typeof (int); }
    }

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

        ViewGroup.LayoutParams layoutParameters = realTarget.LayoutParameters;
        realTarget.LayoutParameters = new LinearLayout.LayoutParams(layoutParameters.Width, layoutParameters.Height,
                                                                  (int) value);
    }
}

registration in setup:

protected override void FillTargetFactories(IMvxTargetBindingFactoryRegistry registry)
{
    registry.RegisterFactory(new MvxSimplePropertyInfoTargetBindingFactory(typeof(ViewWeightCustomBinding), typeof(View), "ViewWeight"));
    base.FillTargetFactories(registry);
}

And .axml

 <View
        android:layout_width="0dp"
        android:layout_height="3dp"
        android:background="@color/green_holo"
        local:MvxBind="ViewWeight Id" />

I can see Waring in debug window:

[0:] MvxBind:Warning: 5.20 Failed to create target binding for binding ViewWeight for Id [0:] MvxBind:Warning: 5.20 Failed to create target binding for binding ViewWeight for Id 01-31 10:54:57.247 I/mono-stdout( 3795): MvxBind:Warning: 5.20 Failed to create target binding for binding ViewWeight for Id

回答1:

MvxSimplePropertyInfoTargetBindingFactory can only be used for real C# properties.

For invented "pseudo" properties, you need to use a custom binding registration like that shown in the n=28 tutorial -

    protected override void FillTargetFactories(Cirrious.MvvmCross.Binding.Bindings.Target.Construction.IMvxTargetBindingFactoryRegistry registry)
    {
        registry.RegisterCustomBindingFactory<BinaryEdit>(
                        "N28", 
                        binary => new BinaryEditFooTargetBinding(binary) );
        base.FillTargetFactories(registry);
    }

https://github.com/MvvmCross/NPlus1DaysOfMvvmCross/blob/master/N-28-CustomBinding/CustomBinding.Droid/Setup.cs