Reputation: 3101
I want to get data from the SelectedItem in CollectionView, but doing that I must work with SelectionChanged_EventHandler(object sender, SelectionChangedEventArgs e) which appear to be inside the Back-end code of the Content Page. I want to process this work inside my ViewModel code instead as I have to pass the data from SelectedItem to my ObservableCollection<> in the ViewModel code.
Is there any method that I can get data from the SelectedItem in CollectionView and also handle this event inside my ViewModel code?
Upvotes: 1
Views: 4076
Reputation: 1304
Yes! There are several ways to do this:
1) Using SelectedItem Bindeable property to trigger the event
XAML:
<CollectionView
SelectedItem="{Binding SelectedItem}" ..../>
ViewModel:
public Item SelectedItem
{
get { return _selectedItem; }
set
{
if (value == _selectedItem)
return;
_selectedItem = value;
TriggerMethodThatYouWant();
OnPropertyChanged(nameof(BackgroundTest));
}
}
2) Using a TapGestureRecognizer: this will trigger On Tapping, is different that selection but achieves the same
Xaml:
<CollectionView
ItemsSource="{Binding Items}">
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout>
<StackLayout.GestureRecognizers>
<TapGestureRecognizer Command="{Binding tapCommand}" CommandParameter="{Binding .}"/>
</StackLayout.GestureRecognizers>
</DataTemplate>
</CollectionView.ItemTemplate>
<CollectionView>
Viewmodel: You will have to create the command and the method
public Command<Item> tapCommand { get; }
Upvotes: 3