【问题标题】:Using MvvmCross to Bind to layout_width and layout_height使用 MvvmCross 绑定到 layout_width 和 layout_height
【发布时间】:2014-03-28 00:08:14
【问题描述】:

是否可以使用 MvvmCross 将对象的高度绑定到 viewmodel 中的属性?

<ImageView
android:src="@drawable/blue_cat_icon"
android:layout_width="wrap_content"
android:layout_height="match_parent"
local:MvxBind="layout_height User.Height; layout_width User.Width" />

如果没有定义 layout_height 或 layout_width,Xamarin 工作室会抱怨,所以我希望有一种方法可以通过绑定来覆盖属性。

我有五个图标,我只希望其中一个根据 VM 的属性变大,我还假设我将使用值转换器。

【问题讨论】:

    标签: android mvvmcross


    【解决方案1】:

    我认为为此采取的方法类似于How to bind to View's layout_weight in MvvmCross?中的方法

    1。为您的缩放添加一个类型 - 例如

    public class Scaling
    {
        public double Height {get; private set;}
        public double Width {get; private set;}
    
        // ctor
    }
    

    2。也为该类型添加一个属性

    public Scaling CurrentScaling
    {
        get { return _scaling; }
        set { _scaling = value; RaisePropertyChanged(() => CurrentScaling); }
    }
    

    3。在视图项目中添加一个知道缩放的自定义绑定

    public class ViewScalingCustomBinding : MvxAndroidTargetBinding
    {
        public ViewScalingCustomBinding(object target) : base(target)
        {
        }
    
        public override Type TargetType
        {
            get { return typeof (Scaling); }
        }
    
        protected override void SetValueImpl(object target, object value)
        {
            var realTarget = target as View;
            if(target == null)
                return;
    
            var scaling = value as Scaling;
    
            ViewGroup.LayoutParams layoutParameters = realTarget.LayoutParameters;
            realTarget.LayoutParameters = new LinearLayout.LayoutParams(scaling.Width, scaling.Height);
        }
    }
    

    4。在视图项目中注册了解 Scaling 的自定义绑定

    protected override void FillTargetFactories(Cirrious.MvvmCross.Binding.Bindings.Target.Construction.IMvxTargetBindingFactoryRegistry registry)
    {
        registry.RegisterCustomBindingFactory<View>(
                        "ScaleMe", 
                        v => new ViewScalingCustomBinding(v) );
        base.FillTargetFactories(registry);
    }
    

    5。使用绑定

    local:MvxBind="ScaleMe CurrentScaling"
    

    注意:

    • 用于LayoutParameters 的类型取决于容器 - 在上面的这段代码中,我使用了LinearLayout
    • 以上代码均未经过测试 - 但一般方法应该可以工作
    • 如果您使用的是 API 11 或更高版本,那么另一种方法是使用 Android ViewScaleXScaleY 属性 - 这是我更喜欢使用的。

    【讨论】:

      猜你喜欢
      • 2016-05-19
      • 2016-04-24
      • 2013-10-07
      • 2013-06-09
      • 2015-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多