Reputation: 2964
I'm using Xamarin Forms and I want to add three labels with three different colours inside a container so when the container is pressed it invokes an event handler.
Upvotes: 2
Views: 969
Reputation: 34013
For this you can use the Gestures
.
There are a couple of default recognizers available in Xamarin.Forms, including the TapGestureRecognizer
.
You can add them to virtually any visual element. Have a look at a simple implementation which binds to an Image
.
var tapGestureRecognizer = new TapGestureRecognizer();
tapGestureRecognizer.Tapped += (s, e) => {
// handle the tap
};
image.GestureRecognizers.Add(tapGestureRecognizer);
Or in XAML:
<Image Source="tapped.jpg">
<Image.GestureRecognizers>
<TapGestureRecognizer
Tapped="OnTapGestureRecognizerTapped"
NumberOfTapsRequired="2" />
</Image.GestureRecognizers>
</Image>
As you can see you can also set the NumberOfTapsRequired
to enable it for more taps before it takes action.
You can use Commands
instead as well.
Other gestures are Pinch and Pan and the documentation on Tap can be found here.
In a example for what you are asking specifically try something like this:
<StackLayout>
<StackLayout.GestureRecognizers>
<TapGestureRecognizer Tapped="handle" />
</StackLayout.GestureRecognizers>
<Label x:Name="myLabel" Text="Open Search" FontSize="30" TextColor="Blue" />
<Label x:Name="myLabel2" Text="URL" FontSize="30" TextColor="Green" />
</StackLayout>
This handles the gesture for the whole group.
If you want it per Label
, do this:
<Label x:Name="myLabel2" Text="URL" FontSize="30" TextColor="Green">
<Label.GestureRecognizers>
<TapGestureRecognizer Tapped="handle" />
</Label.GestureRecognizers>
</Label>
Upvotes: 5