ViewModel's constructor is being called again on navigation, and so messenger subscriptions are being subscribed again

后端 未结 1 867
逝去的感伤
逝去的感伤 2021-01-20 00:41

I am building a cross-platform mobile application using MvvmCross framework.

Since I would like to share information between ViewModels, I am registerin

相关标签:
1条回答
  • 2021-01-20 01:19

    Explanation on why the constructor is being called again, and how to avoid that.

    The ctor is not called twice on the same object - instead what might happen is that a new View and a new ViewModel are created each time.

    By default I would expect a new ViewModel to be created on every forwards navigation on every platform.

    By default I would **not expect this to happen during a back button on WindowsPhone - it doesn't happen here for my test cases - but it could happen if:

    • WindowsPhone removes your first Page (and it's ViewModel) from memory - I guess this might happen if your app is tombstoned or if you are using a custom RootFrame - but I don't expect this to happen by default.
    • you somehow null the ViewModel (DataContext) in your first Page

    Without seeing more of your code I can't guess any more about why this might happen.


    I'd personally recommend you look deeper at why you are seeing new ViewModels created during Back, but if you just want a quick fix, then you could look at overriding the ViewModelLocator within MvvmCross - see MvvmCross: Does ShowViewModel always construct new instances?


    Note that on WindowsStore, I would expect this to happen - WindowsStore doesn't hold Pages from the backstack in memory by default - but you can overriding this by setting NavigationCacheMode = NavigationCacheMode.Enabled; if you need to.

    0 讨论(0)
提交回复
热议问题