如何在MvvmCross中绑定到View的layout_weight?

时间:2014-01-31 10:13:25

标签: xamarin.android xamarin mvvmcross

绑定到View(或任何其他Android控件)权重的最简单方法是什么?因为这个属性没有setter,所以我尝试了自定义绑定,但id似乎不起作用:

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

在设置中注册:

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

和.axml

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

我可以在调试窗口中看到Waring:

  

[0:]   MvxBind:警告:5.20无法为绑定ViewWeight for Id创建目标绑定   [0:] MvxBind:警告:5.20无法为绑定ViewWeight for Id创建目标绑定   01-31 10:54:57.247 I / mono-stdout(3795):MvxBind:警告:5.20无法创建绑定ViewWeight for Id的目标绑定

1 个答案:

答案 0 :(得分:1)

MvxSimplePropertyInfoTargetBindingFactory只能用于真正的C#属性。

对于发明的“伪”属性,您需要使用自定义绑定注册,如n = 28教程中所示 -

    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