Search code examples
c#xamarinxamarin.formsxamarin.forms.collectionview

How can I add a SelectionChanged in a CollectionView from code?


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.


Solution

  • 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
       }
    };