How to get the index of a clicked CollectionView element?

﹥>﹥吖頭↗ 提交于 2021-02-05 12:15:55

问题


I have elements added inside a CollectionView. Inside this CollectionView, I have an ImageButton wich 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 posible?

My 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

回答1:


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

For example:

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
    }

}

the 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


来源:https://stackoverflow.com/questions/65938216/how-to-get-the-index-of-a-clicked-collectionview-element

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!