Search code examples
event-handlingpopupcustom-controlsmaui

How do I create a clickable custom control?


My custom control:

<?xml version="1.0" encoding="utf-8" ?>
<ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="OneCampus.Components.TimeEntryCard"
             x:Name="TimeCardEntryView">

    <VerticalStackLayout>
        <Frame BackgroundColor="Blue" 
               HorizontalOptions="Fill">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="*" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>
                <Label Text="{Binding Source={x:Reference TimeCardEntryView}, Path=Day}" 
                       HorizontalOptions="Start" VerticalOptions="Center" Grid.Row="0" Grid.Column="0" />
                <VerticalStackLayout VerticalOptions="Center" Grid.Row="0" Grid.Column="1">
                    <Label Text="InTime" HorizontalOptions="Center" />
                    <Label Text="OutTime" HorizontalOptions="Center" />
                </VerticalStackLayout>
                <Label Text="TotalTime" HorizontalOptions="End" VerticalOptions="Center" Grid.Row="0" Grid.Column="2" />
            </Grid>
        </Frame>
    </VerticalStackLayout>
    
</ContentView>
namespace OneCampus.Components;

public partial class TimeEntryCard : ContentView
{
    // does this need to be "public static??"
    public static readonly BindableProperty DayProperty = BindableProperty.Create(nameof(Day), typeof(string), typeof(TimeEntryCard), string.Empty);

    public string Day
    {
        get => (string)GetValue(DayProperty);
        set => SetValue(DayProperty, value);
    }

    public TimeEntryCard()
    {
        InitializeComponent();
    }
}

Output:
actual front-end


What I need:

I need the blue frame to be clickable so that whenever the user clicks on it, it should open a popup. How do I go about it? I am guessing creating a Clicked property on the custom control, but I don't know where to begin.


Solution

  • use a Gesture Recognizer

    <Frame.GestureRecognizers>
        <TapGestureRecognizer
                Tapped="OnTapGestureRecognizerTapped"
                NumberOfTapsRequired="1" />
    </Frame.GestureRecognizers>
    

    then in your code behind

    void OnTapGestureRecognizerTapped(object sender, EventArgs args)
    {
    }
    

    you can also use Command instead of Tapped to specify a command in your VM instead of an event handler in your code behind