I have a very simple, single paged .NET MAUI piece of code. The XAML contains 4 Labels and 1 Image. The 1st Label has a TapGestureRecognizer
with a Tapped
event. When tapped, the 2nd Label Text changes. This works fine.
My 3rd Label similarly has a TapGestureRecognizer
, but this time uses a Command
which links back to the code behind and when tapped, changes the Text in the 4th Label.
If the Image is tapped, the 4th Label Text changes.
That’s the theory. The reality is that only the TapGestureRecognizer
with the Tapped
event does anything.
My XAML looks like this
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="TapGestureRecognizer.MainPage" >
<VerticalStackLayout Padding="8" HorizontalOptions="Center">
<Label Text="Please tap me" FontSize="16" Margin="0,8">
<Label.GestureRecognizers>
<TapGestureRecognizer NumberOfTapsRequired="1" Tapped="LabelTapped" />
</Label.GestureRecognizers>
</Label>
<Label Text="" Padding="8" TextColor="Red" x:Name="uiLabel" />
<Label Text="Please tap me here" FontSize="16" Margin="0,8">
<Label.GestureRecognizers>
<TapGestureRecognizer NumberOfTapsRequired="1" Command="{Binding LabelTappedCommand}" />
</Label.GestureRecognizers>
</Label>
<Label Text="" Padding="8" TextColor="Red" x:Name="uiLabel2" />
<Image Source="dotnet_bot.png" WidthRequest="100" HeightRequest="100">
<Image.GestureRecognizers>
<TapGestureRecognizer NumberOfTapsRequired="1" Command="{Binding LabelTappedCommand}" />
</Image.GestureRecognizers>
</Image>
</VerticalStackLayout>
</ContentPage>
The code behind is this
using System.Windows.Input;
namespace TapGestureRecognizer;
public partial class MainPage : ContentPage
{
bool _selected = false;
bool _otherSelected = false;
public ICommand LabelTappedCommand { get; set; }
public MainPage()
{
InitializeComponent();
BindingContext = this;
LabelTappedCommand = new Command(() =>
{
uiLabel2.Text = !_otherSelected ? "Wax on" : "Wax off";
_otherSelected = !_otherSelected;
});
}
void LabelTapped(object sender, TappedEventArgs e)
{
uiLabel.Text = !_selected ? "Hello" : "Goodbye";
_selected = !_selected;
}
void OnTapped()
{
uiLabel2.Text = !_otherSelected ? "Wax on" : "Wax off";
_otherSelected = !_otherSelected;
}
}
The OnTapped method is there as I changed the lambda in case that was the issue – the lambda previously called the OnTapped method.
Does anyone have any insights on why the 3rd Label or the Image is not firing the code behind?