Trevor Balcom
Trevor Balcom

Reputation: 3888

TextView Compound Drawable MvvmCross Binding

TextView has some DrawableXXX properties like DrawableStart, DrawableEnd, DrawableTop, etc. to show a Drawable next to the TextView text. Is it possible to bind this property using MvvmCross? I've tried using local:MvxBind="Drawablename 'check'" in my binding but it fails showing an MvxBind error:

Failed to create target binding for binding DrawableName for check

If this binding is not implemented in MvvmCross then how would I go about doing this on my own? Is the method used by N+28 still the recommended way to add a custom binding?

Upvotes: 1

Views: 377

Answers (1)

Plac3Hold3r
Plac3Hold3r

Reputation: 5182

There is not currently any MvvmCross define target binding for adding compound drawables. However, you can easily add your own. If you are using MvvmCross 5+ you can take advantage of the new typed custom binding classes. Note, the example below has set the drawable to be placed on the left, however, you can choose to place at any direction (or multiple).

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

Then register in your Setup.cs

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

Then in your XML you can use

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

Upvotes: 2

Related Questions