3

We have a windows phone 8 application in which we are using mvvm light having four , five views , and about same number of view models. One day we observed that the size of the application is increasing with usage and eventually reaches more than 100 mb and eventually crashes.After lot of testing what we are able to understand is that every time we navigate to a view , its instance is created and stored in the memory.It was observed that all the instances of the view and the view model are living in the memory and thus increasing the space on the ram. We also confirmed the same by defining finializer on view class and view model , on closing the application the finializer is called exactly the same number of times the page was navigated to. We are binding the datacontext of the view to respective view model in xaml. One of the main view has an ad control , so size increases very fast if user navigates to that view multiple times. How to resolve this issue. What I am unable to understand is the view should be destroyed once the user presses the back button, but this is not happening . Any help would be much appreciated.

Gaurav
  • 113
  • 6

3 Answers3

1

We found a solution to this by adding below line of code to code behind.

protected override void OnNavigatedFrom(NavigationEventArgs e)
    {
        base.OnNavigatedFrom(e);
        Messenger.Default.Unregister(this);

        if (e.NavigationMode == NavigationMode.Back)
        {
            DataContext = null;
        }
    }

What we are doing above is that we are unregisterring all the message handlers for the page and assigning the DataContext to null. In our case the datacontext was assigned in the xaml only and messenge handlers were registered in the OnNavigatedTo event of the page. But what is still unclear that on navigating back from the page , the page object should have died automatically . And should this line of code be added to all the mvvm light project pages and if so then why is it not common practice.

Gaurav
  • 113
  • 6
0

The reason you are leaking View memory is because you are in some way subscribing to events of the ViewModel from inside your Views. Either refactor those subscriptions to be WeakEvent subscriptions or remove them inside your OnNavigatedFrom

atomaras
  • 2,468
  • 2
  • 19
  • 28
-1

Use an IOC Container to maintain a single instance of all the ViewModels.

One of the options would be to use SimpleIoc that comes with MVVM Light.

Best tutorial to learn MVVMLight SimpleIoc

Community
  • 1
  • 1
Harsha Bhat
  • 718
  • 10
  • 25