xamarin - 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)
{
....
}
解决方案
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 的通用模板所取代
推荐阅读
- java - 如何为对象数据类型进行 POST?
- react-native - 如何使用 rn-cli.config 启用 'require(*/*.vrx)'?
- javascript - Phaser JS:如何在静态组中移动对象
- r - R:仅在新包中使用 data.tables 时加载会在键控子集上出现错误
- javascript - 如何连接两个字符串并搜索记录
- java - 为什么for循环中的三元运算符会出错?
- javascript - 不返回值
- html - 如何在邮件中发送个性化链接?
- mysql - 如何通过路由将我从 Node.js 的 db 获得的数据发送到前端 JavaScript 文件?
- python - 将 CSV 转换为 JSON。如何保持具有相同索引的值?