如何从 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- 使用此 question 中提到的 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;
,

尝试使用 Button1.Parent.Parent.Parent... 等,除非您得到 listview 的对象。

同时在按钮的 BindingContext 中传递 viewcellCommandParameter,例如 CommandParameter={Binding},然后从 ItemsSource 获取您收到的对象的索引。