The Clicked event connects a user activation to application logic. In .NET MAUI, assign a handler to a Button or MenuFlyoutItem so the handler runs when the user clicks it. section 3.2 section 10.3.3
Use Clicked when the interaction needs procedural work in an event handler:
- Rename a button’s handler reference, such as changing OnCounterClicked to OnFindMeClicked. section 3.2
- Perform asynchronous work from the handler, such as checking location permission before sharing a user’s location. section 3.2
- Choose Command instead when a MenuFlyoutItem should invoke logic through its binding context rather than code-behind. section 10.3.3
FindMe button
A button click invokes OnFindMeClicked. The handler checks LocationWhenInUse permission, displays an error or requests permission when necessary, and calls ShareLocation after permission is granted. section 3.2
Listing 3.6 OnFindMeClicked method
private async void OnFindMeClicked(object sender, EventArgs e) #1
{
var permissions = await Permissions.
CheckStatusAsyn<Permissions.LocationWhenInUse>(); #2
if (permissions == PermissionStatus.Granted) #3
{
await ShareLocation(); #4
}
else
{
await App.Current.MainPage.DisplayAlert(
"Permissions Error", "You have not granted the app
permission to access your location.", "OK"); #5
var requested = await Permissions.RequestAsync<
Permissions.LocationWhenInUse>(); #6
if (requested == PermissionStatus.Granted) #7
{
await ShareLocation(); #8
}
else
{
if (DeviceInfo.Platform == DevicePlatform.iOS ||
DeviceInfo.Platform == DevicePlatform.MacCatalyst) #9
{
await App.Current.MainPage.DisplayAlert(
"Location Required", "Location is required to
share it. Please enable location for this app
in Settings.", "OK"); #10
}
else
{
await App.Current.MainPage.DisplayAlert("Location Required", #11
"Location is required to share it. We'll ask again next time.", "OK");
}
}
}
}
Inspect the complete asynchronous handler pattern, including permission checking, permission requests, alerts, and the follow-up action. section 3.2
