doorman
doorman

Reputation: 16949

EventToCommand using Mvvmlight and xamarin forms

When developing for all three mobile platforms using MvvmLight with Xamarin forms, what is the recommended way of binding an event in the view to a command in the viewmodel for events that do not support the command pattern? Is it possible to use EventToCommand?

Thanks!

Upvotes: 2

Views: 1079

Answers (1)

JordanMazurke
JordanMazurke

Reputation: 1123

Not sure about MVVMLight but what you could do is define the Events in an Interface (IPageLifeCycleEvents) which are implemented in the relevant ViewModel. Within the View you would then set the BindingContext as an instance of type IPageLifeCycleEvents and pass the events from the View to the ViewModel through the interface. E.G.

public interface IPageLifeCycleEvents
{
    void OnAppearing ();
    void OnDisappearing();
    void OnLayoutChanged();
}

public class SampleView : ContentPage
{
    public BaseView () {
        var lifecycleHandler = (IPageLifeCycleEvents) this.BindingContext;
        base.Appearing += (object sender, EventArgs e) => {
            lifecycleHandler.OnAppearing();
        };

        base.Disappearing += (object sender, EventArgs e) => {
            lifecycleHandler.OnDisappearing ();
        };

        base.LayoutChanged += (object sender, EventArgs e) => {
            lifecycleHandler.OnLayoutChanged();
        };
    }
}

public class SampleViewModel : IPageLifeCycleEvents
{


    #region IPageLifeCycleEvents Methods

    public void OnAppearing ()
    {
        //Do something here
    }

    public void OnDisappearing ()
    {
        //Do something here
    }

    public void OnLayoutChanged ()
    {
        //Do something here
    }

    #endregion
}

in my actual implementations I use a slightly different setup because of the utilisation of IOC and Base models.

Good luck

Upvotes: 1

Related Questions