Forum Xamarin Xamarin.Forms

Command calls multiplied by number of time a page is navigated to?

Hello, I posted a focused project to illustrate:
https://github.com/BullCityCabinets/MyVMsCommandMultiplies201018

There are 2 Pages: "Order Summary" and "Inventory List"
Both have binding contexts set to static instances of view models.
Inventory List is navigated to by a button's command.
Order Summary is returned to by the back button.

The first time using Inventory List, CollectionView's SelectedItem Command fires once per item tapped.
Then navigate away and return... CollectionView's SelectedItem Command fires twice per item tapped.
Then navigate away and return... CollectionView's SelectedItem Command fires three times per item tapped, and so on!

What could be going on? There are tons of Debug.Writelines to track what happens... which I hope is helpful. The haziest area for me is probably the NavigationService, which I've pulled from a tutorial. I've tried to reduce as many of the other factors as I can see, though.

It's not impacting function, on the surface... but I can't imagine this is a good way to begin!

Posts

  • LardeCristoLardeCristo Member ✭✭

    Hi!! For me the problem is "OnMySelectionChangedCommandCount++". ++ add 1 in your variable.
    First - 1
    Second - 2

    And son on.

    Modify this line
    MySelectionChangedCommand = new Command<object>(OnMySelectionChangedCommand);
    to
    MySelectionChangedCommand = new Command<object>( { OnMySelectionChangedCommandCount = 0; OnMySelectionChangedCommand(); });

  • ScumSprocketScumSprocket Member ✭✭
    edited October 19

    I'm sorry, but I don't follow you, and it causes compile errors. All the "Count++'s" are just to illustrate the issue with Debug.Writeline. Removing doesn't impact the number of times the method is called, when I try it.

    I added a video to help show the issue, in case I'm not clear :
    https://github.com/BullCityCabinets/MyVMsCommandMultiplies201018/blob/main/Presentation1.mp4

  • ScumSprocketScumSprocket Member ✭✭
    edited October 20

    I ended up removing the NavigationService I'd used from a Pluralsight course... it's not completely clear what the point of it was, anyhow. Most MVVM talks seems to suggest I shouldn't have the navigation in the view's code behind, but it solved my problem. I'd still like to know what's going on... pleanty more hic-ups to come, I suspect.

  • JoeMankeJoeManke USMember ✭✭✭✭✭

    I assume your navigation service was creating a new page instance every time you navigated, and you say you're using a singleton instance for the view model. Things probably weren't being disposed properly so you end up with multiple pages bound to a single view model.

  • ScumSprocketScumSprocket Member ✭✭

    Yeah... that sounds reasonable. I guess I just shouldn't be messing with chunks of code I don't understand, yet.

Sign In or Register to comment.