c# - 如何从 Xamarin Forms 中的自定义 ViewCell 获取 ListView 项目索引?
问题描述
我创建了一个具有自定义 ViewCell 的 ListView,如下所示:
<ListView x:Name="ListView1" ItemTapped="ListView1_ItemTapped"
SeparatorVisibility="None" RowHeight="192" HasUnevenRows="False"
FlowDirection="RightToLeft" CachingStrategy="RecycleElement" >
<ListView.ItemTemplate>
<DataTemplate>
<custom:ViewCell1 />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
这是自定义 ViewCell 的 XAML
<ViewCell.View>
<StackLayout>
<Label Text="{Binding Name}" />
<Label Text="{Binding ID}" />
<Button x:Name="Button1" Text="Get index" Clicked="Button1_Clicked" />
</StackLayout>
</ViewCell.View>
我所需要的只是当我单击 Button1 时,我得到 ListView1 项目索引(或 ViewCell 索引)
问题是我无法从自定义 ViewCell 后面的代码中的 Button1_Clicked 事件访问 ListView1 并获取 ListView1 的轻敲项目索引(甚至获取 ViewCell 轻敲项目索引)。
我搜索了很多,发现可以通过3种方式完成:
1- 为 ViewCell 创建一个附加属性以获取其索引。
2- 使用 ViewCell 的索引器并获取它的索引。
3-使用此问题中提到的 ITemplatedItemsView 界面
但不幸的是,我无法从后面的自定义 ViewCell 代码中的 Button1_Clicked 事件中实现它们中的任何一个,因为我不是 MVVM 或 C# 方面的专家。
请给我一个专家帮助。
谢谢
解决方案
有很多方法可以实现它。如果您不熟悉数据绑定和 MVVM。我将提供最简单的方法。
首先,在 ItemSource 的模型中添加一个属性。
public class YourModel
{
public int Index { get; }
//other properties like name and ID
public YourModel(int index)
{
Index = index;
}
}
并在初始化 ListView 的 ItemSource 时设置Index的值。
sources = new ObservableCollection<YourModel>() { };
for(int i=0;i<20;i++)
{
sources.Add(new YourModel(i) { /**other propertes**/});
}
在自定义单元格中
得到它像下面
var model = this.BindingContext as YourModel;
int index = model.Index;
推荐阅读
- python - 将 Selenium find_element_by_name 分成多个阶段
- c# - C# .NET Core WPF - 捕获 WebBrowser 响应
- amazon-web-services - Collibra 从托管在供应商 AWS 账户上的 DGC 实例连接到公司网络内 EC2 上的 SQL Server
- fluent-bit - FluentBit:添加动态es索引
- mongodb - mongoDB中的聚合查询问题
- angular - 在 Angular 项目之外存在的 Angular(chrome)中调试(vscode)打字稿文件
- ssl - OpenSSL 1.0.1 SSL_read() 函数在某些 https 网站上返回 0 字节
- spring-boot - BuildPack 无法解析 gradle 多项目 java springboot 代码的工件
- postgresql - Kafka用例替换控制M作业
- node.js - WSL2 上的 NVM:无法安装节点,找不到版本