如何获取单击的 CollectionView 元素的索引? [英] How to get the index of a clicked CollectionView element?

查看:24
本文介绍了如何获取单击的 CollectionView 元素的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 CollectionView 中添加了元素.在这个 CollectionView 中,我有一个 ImageButton,它使其他 ImageButton 可见.我需要通过单击第一个 ImageButton 来获取元素的索引,并在第二个 ImageButtonCommand 中使用它.这可能吗?

I have elements added inside a CollectionView. Inside this CollectionView, I have an ImageButton which make visible other ImageButton. I need to get the index of the element by clicking the first ImageButton and use it in the Command of the second ImageButton. Is that possible?

我的 xaml:

<StackLayout>
    <CollectionView ItemSource="{Binding myItemSource}">
        <CollectionView.ItemTemplate>
            <DataTemplate>
                <ContentView>
                    <ImageButton x:Name="FirstImageButton" Command={Binding MakeVisibleNewButton}/>
                </ContentView>
            </DataTemplate>
        </CollectionView.ItemTemplate>
    </CollectionView>
    <ImageButton x:Name="SecondImageButton" Command={Binding xxxCommand} IsVisible={Binding VisibleByFirstButton} />
</StackLayout

推荐答案

正如 Jason 所说,您可以通过在 ItemSource 中查找所选项目来获取索引.

As Jason said,you could get the index by looking up the selected item in the ItemSource.

例如:

public class YourViewModel
{
   public List<yourmodel> myItemSource{ get; set; }
   public ICommand MakeVisibleNewButton{ get; set; }
    public YourViewModel()
    {
        ... //fill the myItemSource
        MakeVisibleNewButton= new Command<Productor>(ImageButtonClicked);
    }

    private void ImageButtonClicked(yourmodel obj)
    {
       int index = myItemSource.IndexOf(obj); //the index is what you want to get
    }

}

xaml:

<StackLayout>
  <CollectionView x:Name ="collectionview" ItemSource="{Binding myItemSource}">
      <CollectionView.ItemTemplate>
        <DataTemplate>
            <ContentView>
                <ImageButton x:Name="FirstImageButton" Command="{Binding BindingContext.MakeVisibleNewButton,Source={x:Reference collectionview}}" CommandParameter="{Binding .}"/>
            </ContentView>
        </DataTemplate>
      </CollectionView.ItemTemplate>
   </CollectionView>
   <ImageButton x:Name="SecondImageButton" Command={Binding xxxCommand} IsVisible={Binding VisibleByFirstButton} />
</StackLayout

这篇关于如何获取单击的 CollectionView 元素的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆