0

I would like to call a function when a cell of a Collection View (created in cs) were tapped.

Here is the code:

new StackLayout { Orientation = StackOrientation.Horizontal,
                  HorizontalOptions = LayoutOptions.FillAndExpand,
                  VerticalOptions = LayoutOptions.FillAndExpand,
                  HeightRequest = 200,
                  Children = {
                       new CollectionView {
                           HorizontalOptions = LayoutOptions.FillAndExpand,
                           SelectionMode = SelectionMode.Single,
                           ItemTemplate = MainPage.cv.ItemTemplate,
                           ItemsLayout = MainPage.cv.ItemsLayout,
                           ItemsSource = MainPage.jsonList.Where(x => x.Giorno == MainPage.day && x.Pasto == Pasto_Array[i]),
                       }
                           //.SelectionChanged +=CheckDuplicazioni_SelectionChanged;
                   }
                 }

As you can see I've tried to do using the code commented, but it doesn't work. In XAML file I've used the SelectionChanged function and it worked, why in cs id doesn't?

Waiting for a your feedback, thank you.

Cfun
  • 8,442
  • 4
  • 30
  • 62
  • c# does not allow you to assign event handlers in property initizlizers. Either use the SelectionChangedCommand, or assign your CollectionView to a variable and assign the SelectionChange handler after the property initializer – Jason Jun 11 '21 at 13:09

1 Answers1

2

You can do it by saving the CollectionView instance in a variable

var collectionView = new CollectionView()
{
    HorizontalOptions = LayoutOptions.FillAndExpand,
    SelectionMode = SelectionMode.Single,
    ItemTemplate = MainPage.cv.ItemTemplate,
    ItemsLayout = MainPage.cv.ItemsLayout,
    ItemsSource = MainPage.jsonList.Where(x => x.Giorno == MainPage.day && x.Pasto == Pasto_Array[i]),
};

collectionView.SelectionChanged += CheckDuplicazioni_SelectionChanged;

new StackLayout
{
    Orientation = StackOrientation.Horizontal,
    HorizontalOptions = LayoutOptions.FillAndExpand,
    VerticalOptions = LayoutOptions.FillAndExpand,
    HeightRequest = 200,
    Children = {
        collectionView
   }
};
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Cfun
  • 8,442
  • 4
  • 30
  • 62