Search code examples
xaml.net-coremvvmmauimaui-community-toolkit

How to add on Click event on entire DataTemplate inside MAUI Collection View


How can I add a full template click handler for each item in a MAUI CollectionView?

I have seen the documentation about TapGestureRecognizer but it is not clear to me how to do it for a competitive element, for example in my case inside a HorizontalStackLayout

 <CollectionView ItemsSource="{Binding Items}">
    <CollectionView.ItemTemplate>
        <DataTemplate x:DataType="{x:Type dtos:ItemDto}">
            <HorizontalStackLayout>
                <Image WidthRequest="75" HeightRequest="75" Source="item_default.png"></Image>
                <StackLayout Orientation="Vertical">
                    <Label Text="{Binding Name}" FontSize="Title" />
                    <Label Text="{Binding Description}" FontSize="Subtitle"/>
                </StackLayout>
            </HorizontalStackLayout>                
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

What I want is to open a detail view of each item in case of pressing on it.

Side note: I'm also using CommunityToolkit (MVVM and MAUI ones)

Any ideas? Many thanks!


Solution

  • Thanks to the comment provided at the beginning from @Jason, at the end I opted for a simple approach with the events of the CollectionView:

    XAML:

    <CollectionView 
        ItemsSource="{Binding Items}" 
        SelectionMode="Single" x:Name="ItemsCollectionView"
        SelectionChangedCommand="{Binding ClickCommand}" 
        SelectionChangedCommandParameter="{Binding SelectedItem, Source={x:Reference ItemsCollectionView}}"
    

    ViewModel

    [RelayCommand]
    private async Task ClickAsync(PlaceDto place)
    {
         //Handle logic
    }
    

    Thanks all for the comment and suggestions