XAML Views(Code Behind)

namespace MauiApp1;

public partial class MainPage : ContentPage
{
	int count = 0;

	public MainPage()
	{
		InitializeComponent();
	}

	private void OnCounterClicked(object sender, EventArgs e)
	{
		count++;

		if (count == 1)
			CounterBtn.Text = $"Clicked {count} time";
		else
			CounterBtn.Text = $"Clicked {count} times";

		SemanticScreenReader.Announce(CounterBtn.Text);
	}
}

Let’s look closer some items.

:ContentPage : The class MainPage inherits from ContentPage, which is a class representing a page that displays a single view.

InitializeComponent(); : A method generated by the XAML compiler. Initializes the UI components defined in MainPage.xaml. Binds the XAML elements to their respective objects in the code-behind.

OnCounterClicked : Handles the Clicked event of the button named CounterBtn.

  • object sender: The source of the event; the control that was clicked.
  • EventArgs e: Contains event data.

SemanticScreenReader.Announce(CounterBtn.Text); : Announces the updated button text using the device’s screen reader.