首页 > 解决方案 > 如何从 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# 方面的专家。

请给我一个专家帮助。

谢谢

标签: c#formslistviewxamarinindexing

解决方案


有很多方法可以实现它。如果您不熟悉数据绑定和 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;

推荐阅读