Xamarin.Forms: Subscribing to event handlers VS. commanding

Viewed 2722

Commanding is mainly used to have a clear separation between the ViewModel and the user interface. What is the difference between event subscription and commanding? Consider the following example:

public App ()
{
    Button button = new Button
    {
        Text = "Press me",
    };

    button.Clicked += Button_Clicked;

    // The root page of your application
    MainPage = new ContentPage {
        Content = new StackLayout {
            VerticalOptions = LayoutOptions.Center,
            Children = {
                button,
            }
        }
    };
}

private void Button_Clicked(object sender, EventArgs e)
{
    System.Diagnostics.Debug.WriteLine("Pressed!");
}

VS.

public App ()
{
    Button button = new Button
    {
        Text = "Press me",
    };

    button.Command = new Command(() => System.Diagnostics.Debug.WriteLine("Pressed!"));

    // The root page of your application
    MainPage = new ContentPage {
        Content = new StackLayout {
            VerticalOptions = LayoutOptions.Center,
            Children = {
                button,
            }
        }
    };
}

Regarding memory management one should unsubscribe from the event. Is this also valid for commanding? Where should one subscribe/unsubscribe to/from the event? In OnAppearing() and OnDisappearing()?

1 Answers
Related