Search code examples
c#androidmvvmcross

Bind Alpha Android


I try bind to a ImageView Alpha property, I created a converter to set this for a boolean value. But I don't view setted value.

This is my converter

public class BooleanToOpacity : MvxValueConverter<bool,int>
{
    protected override int Convert(bool value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var boolean = value as bool?;

        if (boolean.Value == true)
        {
            return 1;
        }
        else
        {
            return 127;
        }                
    }

    protected override bool ConvertBack(int value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value > 127)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

I use a Integer value because the Alpha value is 0 to 255.

This my line to binding value.

   local:MvxBind="alpha TwitterPost, Converter=BooleanToOpacity" />

And the Mvx trace me this

   MvxBind:Warning: 11.56 Failed to create target binding for binding alpha for TwitterPost
   [0:] MvxBind:Warning: 11.56 Failed to create target binding for binding alpha for TwitterPost
   10-21 15:54:22.280 I/mono-stdout(12096): MvxBind:Warning: 11.56 Failed to create target binding for binding alpha for TwitterPost

Any idea?

Thanks in advance.


Solution

  • There is no C# property available for "Alpha" in Xamarin.Android, so the Mvx framework doesn't know how to bind to it.

    You could create a custom binding for this if you wanted to - something like:

        public class ImageViewAlphaTargetBinding : MvxAndroidTargetBinding
        {
            public ImageViewAlphaTargetBinding (ImageView target) : base(target)
            {
            }
    
            protected override void SetValueImpl(object target, object value)
            {
                var imageView = (ImageView)target;
                imageView.SetMyProperty((int)value);
            }
    
            public override Type TargetType
            {
                get { return typeof(int); }
            }
        }
    

    registered in Setup.cs with:

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

    Alternatively, you could inherit from ImageView and provide a custom view that exposes an Alpha property.

    For more on both these options, see: