Search code examples
c#xamarin.formscontent-pages

How to process CollectionView On SelectedItem event in ViewModel Code instead of Back-end Code of Content Page? Xamarin.Form


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?


Solution

  • 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; }