如何通过代码在 CollectionView 中添加 SelectionChanged?

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

我想在点击集合视图(在 cs 中创建)的单元格时调用一个函数。

代码如下:

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

如您所见,我已尝试使用注释的代码进行操作,但它不起作用。 在 XAML 文件中我使用了 SelectionChanged 函数并且它起作用了,为什么在 cs id 中不起作用?

等待您的反馈, 谢谢。

您可以通过将 CollectionView 实例保存在变量中来实现

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