Search code examples
xamarin.formsxamarin.androidxamarin.ioscollectionviewsender

Xamarin - How to call a function in Collection View without error?


I'm trying to call a function in a Xamarin project by using the SelectionChanged property. Inside this property, I've called a function that I've declared in the cs file. Here is the XAML code:

<CollectionView x:Name="PCCollection" SelectionMode="Single" SelectionChanged="Cell_Tapped" AutomationId="{Binding Tipologia_Alimento}">

Here is the CS function:

private async void Cell_Tapped(object sender, System.EventArgs e) {
  Console.WriteLine("Tapped");
  Console.WriteLine((sender as Cell).AutomationId.ToString());
}

When I click on the Collection View cell, it prints the value "Tapped" but it gives me also the Break Mode error: "The application is in break mode".

Could you help me with this error? Thanks in advance.


Solution

  • Your syntax is not valid. The Collection View control does not have AutomationId property.

    Sample

           <CollectionView ItemsSource="{Binding Monkeys}"
                        SelectionChanged="Cell_Tapped"
                        SelectionMode="Single">
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <Grid Padding="10">
                        <Label Grid.Column="1"
                       Text="{Binding Name}"
                       FontAttributes="Bold" />
                    </Grid>
                </DataTemplate>
            </CollectionView.ItemTemplate>
    
        void Cell_Tapped(object sender, SelectionChangedEventArgs e)
        {
            if (((CollectionView)sender).SelectedItem == null)
                return;
    
            string current = (e.CurrentSelection.FirstOrDefault() as Monkey)?.Name;
        }
    

    You can find more here

    https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/collectionview/selection

    https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/collectionview/populate-data