Computer Magic Logo
Sharing button clicks

Monday, April 11, 2016

Published by Aristotelis Pitaridis

Sometimes we may have multiple buttons on the form which may have similar functionality and we want to share one member function. Below we can see an example that two buttons share the same member function and when we click one of the buttons, only the text of the button that we clicked will be changed.

public partial class Page1 : ContentPage
{
    public Page1 ()
    {
        InitializeComponent ();

        MyButton1.Clicked += MyButton_Clicked;
        MyButton2.Clicked += MyButton_Clicked;
    }

    private void MyButton_Clicked(object sender, EventArgs e)
    {
        Button ClickedButton = (Button)sender;

        ClickedButton.Text = DateTime.Now.ToString();
    }
}