Computer Magic Logo
Click event

Monday, April 11, 2016

Published by Aristotelis Pitaridis

The button has an event called Clicked which will fire when the user clicks on the button. Below we can see an example which changes the text of the button when the user clicks on it so that the current date and time will appear as text of the button.

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

        MyButton.Clicked += MyButton_Clicked;
    }

    private void MyButton_Clicked(object sender, EventArgs e)
    {
        MyButton.Text = DateTime.Now.ToString();
    }
}

As with any event handler, we can define a click event handler as an anonymous lambda function.

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

        MyButton.Clicked += (sender, args) => 
        {
            MyButton.Text = DateTime.Now.ToString();
        };
    }
}