问题
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