How to create event for subclassed control

Lloyd Sheen 1,476 Reputation points
2024-05-28T15:05:06.46+00:00

I use GestureRecognizers with Label in lots of places in an app and would like to create a new Label control that basically uses Label as the base and adds a TapGestureRecognizer that invokes an event that can be defined in XAML.

I know how to subclass the Label control and add the GestureReconizer/TapGestureRecongizer in C# but not how to create the event that a user can provide to handle the Tap.

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,206 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,625 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Lloyd Sheen 1,476 Reputation points
    2024-05-29T12:50:56.2366667+00:00

    I actually found something simpler.

    It works and not sure if it might have problems but all I needed to do is the following:

    In the control code I added:

    public event EventHandler Tapped;

    and in the DoSomeThingOnTap I added:

    // the ? means that if the Tapped is not set then don't executed it

    Tapped?.Invoke(this, null);