Binding Loosed After Programmatically Mainpage Content Change

vanKraster 181 Reputation points

I have a Page that is normally binded with a viewmodel from code behind in constructor like this:

        BindingContext = this.ViewModel = TinyIoCContainer.Current.Resolve<AggiungiCarrelloPageViewModel>();

So it works perfectly but at some point in my page I have a control that overrides the CurrentPageContent something like this...

if (CurrentContentPage == null)
                CurrentContentPage = Application.Current.MainPage;
 if (CurrentContentPage is NavigationPage)
                CurrentContentPage = (CurrentContentPage as NavigationPage).CurrentPage;

if (CurrentContentPage is ContentPage)
                        (CurrentContentPage as ContentPage).Content = customViewToOverride;

For semplicity I only copy-pasted simple code ... but it Works.... Now the problem is this, when I return back to the DefaultPageContent that I saved in memory (that was before customViewToOverride) like this :

  (CurrentContentPage as ContentPage).Content = DefaultPageContent;

It is working all fine except that all the bindings are nulled even if before I choose something, so I loose the previous state (If I start to select again all values it is working fine). It is possible to maintain the previous state or Xamarin when I change the page content automatically erase all my bindings and I cannot avoid that ?

L.E. I am seeing that the BindingContext remains binded to the DefaultPageContent (even if it is saved in memory)

A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,015 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. vanKraster 181 Reputation points

    I have found the solution:

    Before Saving the Current Page I have saved

      DefaultPageVm = DefaultPageContent.BindingContext; 

    And then I have unbinded the page

    DefaultPageContent.BindingContext = null;

    And on restore after content replace I have rebinded the saved viewmodel

      (CurrentContentPage as ContentPage).Content = DefaultPageContent;
      (CurrentContentPage as ContentPage).BindingContext = DefaultPageVm;

    And now it works.

    0 comments No comments