TextView Compound Drawable MvvmCross绑定

时间:2017-08-08 16:08:45

标签: xamarin.android mvvmcross

TextView有一些DrawableXXX属性,例如DrawableStartDrawableEndDrawableTop等,以显示Drawable旁边的TextView 1}}文字。是否可以使用MvvmCross绑定此属性?我在绑定中尝试使用local:MvxBind="Drawablename 'check'",但无法显示MvxBind错误:

  

无法为绑定DrawableName创建目标绑定以进行检查

如果在MvvmCross中没有实现此绑定,那么我将如何自行完成此操作? N+28使用的方法仍然是添加自定义绑定的推荐方法吗?

1 个答案:

答案 0 :(得分:2)

目前没有任何MvvmCross定义目标绑定用于添加复合drawables。但是,您可以轻松添加自己的。如果您使用的是MvvmCross 5+,则可以利用新的类型自定义绑定类。 注意 ,下面的示例将drawable设置为放置在左侧,但是,您可以选择放置在任何方向(或多个)。

public class CompoundDrawablesDrawableNameBinding : MvxAndroidTargetBinding<TextView, string>
{
    public const string BindingIdentifier = "CompoundDrawableName";

    public CompoundDrawablesDrawableNameBinding(TextView target) : base(target)
    {
    }

    public override MvxBindingMode DefaultMode => MvxBindingMode.OneWay;

    protected override void SetValueImpl(TextView target, string value)
    {
        var resources = AndroidGlobals.ApplicationContext.Resources;
        var id = resources.GetIdentifier(value, "drawable", AndroidGlobals.ApplicationContext.PackageName);
        if (id == 0)
        {
            MvxBindingTrace.Trace(MvxTraceLevel.Warning,
                "Value '{0}' was not a known compound drawable name", value);
            return;
        }

        target.SetCompoundDrawablesWithIntrinsicBounds(
            left: id,
            top: 0,
            right: 0,
            bottom: 0);
    }
}

然后在Setup.cs

中注册
protected override void FillTargetFactories(IMvxTargetBindingFactoryRegistry registry)
{
    base.FillTargetFactories(registry);
    registry.RegisterCustomBindingFactory<TextView>(
        CompoundDrawablesDrawableNameBinding.BindingIdentifier,
        textView => new CompoundDrawablesDrawableNameBinding(textView));
}

然后在您的XML中,您可以使用

local:MvxBind="CompoundDrawableName <<YOUR PROPERTY TO BIND TO>>"