10th November 2014 Olivier

Enable Two-way binding with MVVMCross

 

A quick tip. On a Xamarin Android project with MVVMCross, I had to make some binding on the DisplayedChild property of a ViewFlipper. I needed a two-way binding, but it didn’t work.

After some reading, I understood how binding is working :

– For one way binding, it uses Reflection to get the property (DisplayedChild in my case)

– For two way binding, it uses also Reflection , but is looking for events so it can know when the value is changing.

So, for the two way binding to work, I just have to add an event XXXXChanged. So I created this custom ViewFlipper :

public class CustomViewFlipper : ViewFlipper
    {
        public event EventHandler DisplayedChildChanged;

        protected CustomViewFlipper(IntPtr javaReference, JniHandleOwnership transfer)
            : base(javaReference, transfer)
        {
        }

        public CustomViewFlipper(Context context)
            : base(context)
        {
        }

        public CustomViewFlipper(Context context, IAttributeSet attrs)
            : base(context, attrs)
        {
        }

        public override void ShowNext()
        {
            base.ShowNext();

            if (DisplayedChildChanged != null)
                DisplayedChildChanged(this,new EventArgs());
        }

        public override void ShowPrevious()
        {
            base.ShowPrevious();

            if (DisplayedChildChanged != null)
                DisplayedChildChanged(this, new EventArgs());
        }

    }

That is all ! Just a base event, and raise it when the user changes the FlipperView view. Now the DisplayedChild value is propagated to my VM.

Here is the axml ViewFlipper part :

And the (simplified) VM :

public class StartParkingSessionGPSViewModel : MvxViewModel
    {
        public int SelectedIndex { get; set; }
    }

Mobile and Mixed Reality engineer , Arcana Studio
follow me

, ,

Leave a Reply

Your email address will not be published. Required fields are marked *