首页 > 解决方案 > Xamarin - 从collectionView的单击单元格内的标签获取值

问题描述

我有一个 collectionView,它是通过 Binding 源自动填充的。在每个单元格中,我都有一些标签。当我单击标签时,我需要能够读取其中一个标签的值。(在下面的示例中,它是“PhotographerCode”)这是我到目前为止所拥有的,但我无法弄清楚如何触发事件后从代码中访问标签...

<StackLayout>
        <Button Text="Populate DB" 
                x:Name="populateButton" 
                Clicked="populateButton_Clicked"/>
        <CollectionView ItemsSource="{Binding GalleryList}">
            <CollectionView.ItemsLayout>
                <GridItemsLayout Orientation="Vertical"
                    Span="1" />
            </CollectionView.ItemsLayout>
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <ViewCell x:Name="Cell"  Tapped="Cell_Tapped">
                    <Grid Padding="10" ColumnSpacing="0" RowSpacing="0">


                        <Label Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="3" Text="{Binding GalleryName}" FontSize="Large" BackgroundColor="LightGray"></Label>
                        <Label Grid.Row="1" Grid.Column="0" Text="Photographer: " FontSize="Small"  BackgroundColor="LightGray"></Label>
                        <Label Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="2" Text="{Binding PhotographerName}" FontSize="Default" BackgroundColor="LightGray"></Label>
                        <Label Grid.Row="2" Grid.Column="0" Text="Code: " FontSize="Small" BackgroundColor="LightGray"></Label>
                        <Label x:Name="PhotographerCode" Grid.Row="2" Grid.Column="1" Text="{Binding PhotographerCode}" FontSize="Small" BackgroundColor="LightGray"></Label>
                        <Label Grid.Row="2" Grid.Column="2" Text="{Binding GalleryCode}" FontSize="Small" BackgroundColor="LightGray"></Label>
                    </Grid>
                    </ViewCell>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
    </StackLayout>

和 .cs 文件:

 private void Cell_Tapped(object sender, EventArgs e)
    {
       ....
    }

标签: xamarinlabelcellcollectionview

解决方案


CollectionView内置了对此的支持

<CollectionView ItemsSource="{Binding GalleryList}" SelectionMode="Single" SelectionChanged="OnCollectionViewSelectionChanged">

然后在您的事件处理程序中

void OnCollectionViewSelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var item = (MyModelClass)e.CurrentSelection.FirstOrDefault();

    ....
}

您也不需要(也不应该)将任何 *Cell 元素与 CollectionView 一起使用。这些是 ListView 所必需的,并且已被具有 CollectionView 的通用模板所取代


推荐阅读