Arthurdent510
Arthurdent510

Reputation: 1320

Event handler ordering in Xamarin

I have a list view that I am popping up in Xamarin forms, that I want to hide if someone taps outside of the box. I have a tap gesture recognizer on the parent layout for the list view that handles that. In Android, it all works good. If I click off, it closes, but if I click on an element in the list view, it properly selects it. In iOS, the opposite happens. The gesture handler on the layout fires first and closes the list view without properly selecting the item.

So my question, is there a way to change the order on how the events are fired? If not, is there a better alternative to how I'm trying to accomplish this? Thanks!

Upvotes: 2

Views: 518

Answers (1)

hvaughan3
hvaughan3

Reputation: 11105

If you are using ListView.ItemSelected or ListView.ItemTapped then I ran into the exact same issue the other day. The fix for me was to not use either of those and instead attach a TapGestureRecognizer to the ViewCell that is within the ListView. I also added an IsSelected property to the object that the ViewCell is being bound to so that I could change the background color of the item once it has been clicked.

public class SomePage : ContentPage {

    private SomeModel _selectedModel; //It would be best to put this into your ViewModel

    ...

    public SomePage() {

        ListView list = new ListView {
            ItemTemplate = new DataTemplate(() => {
                ViewCell cell = new ViewCell {
                    View = new ContentView()
                };

                cell.View.GestureRecognizers.Add(new TapGestureRecognizer {
                    Command = new Command(() => {
                        if(_selectedModel != null) { _selectedModel.IsSelected = false; }

                        SomeModel model = (SomeModel)cell.BindingContext;

                        model.IsSelected = true;
                        _selectedModel = model;
                    })
                }

                return cell;
            }
        }
    }
}

Upvotes: 1

Related Questions