首页 > 解决方案 > Xamarin - 如何在集合视图中调用函数而不出错?

问题描述

我正在尝试使用 SelectionChanged 属性调用 Xamarin 项目中的函数。在这个属性中,我调用了一个在 cs 文件中声明的函数。这是 XAML 代码:

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

这是 CS 函数:

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

当我单击 Collection View 单元格时,它会打印值“Tapped”,但它也给了我中断模式错误:“应用程序处于中断模式”。

你能帮我解决这个错误吗?提前致谢。

标签: xamarin.formsxamarin.androidxamarin.ioscollectionviewsender

解决方案


您的语法无效。集合视图控件没有 AutomationId 属性。

样本

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

你可以在这里找到更多

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

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


推荐阅读