【问题标题】:How to get ListView item index from custom ViewCell in Xamarin Forms?如何从 Xamarin Forms 中的自定义 ViewCell 获取 ListView 项目索引?
【发布时间】:2021-05-12 20:52:19
【问题描述】:

我创建了一个具有自定义 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# 方面的专家。

请给我专家帮助。

谢谢

【问题讨论】:

    标签: c# forms listview xamarin indexing


    【解决方案1】:

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

    【讨论】:

    • 非常感谢卢卡斯的简单回答,这正是我所需要的。我正在从包含 ListView 的内容页面初始化 OnAppearing() 事件上的 itemsSource ...您是否建议我应该从自定义 ViewCell 的 OnAppearing() 事件初始化它,以便我可以使用 BindingContext ?
    • 只需要在click事件中获取bindingcontext即可。
    • 谢谢卢卡斯,实际上我只加载了 10 条记录,然后当它到达滚动结束时,它会从数据库中获取下 10 条记录,这会导致 i 值中的索引号重复吗? for(int i=0;i
    • 设置索引从ItemSource的当前长度-1开始。
    • 如果回复有帮助,请采纳为答案(点击此答案左上角的“✔”),对有类似问题的人有帮助。如果您有更多问题,可以创建一个包含更多详细信息的新主题,以便我可以更好地帮助您。
    【解决方案2】:

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

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

    【讨论】:

    • 感谢 Prayag 的快速响应,您能否详细说明如何从 ItemsSource 获取接收对象的索引
    猜你喜欢
    • 2017-09-29
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    • 2020-02-10
    • 2017-07-30
    • 2021-10-27
    • 1970-01-01
    相关资源
    最近更新 更多