Xamarin Forms Content View - unsubscribing from OnPropertyChanged when view unloads

Journeyman42 1 Reputation point
2021-03-26T07:47:38.363+00:00

I have a page in which I load a number of content views

One of those views has a binding context which is different to that of the parent page

Because the view is dynamic (loading comments, allowing users to like / unlike and post), it has OnBindingContext change set

However, when the user returns to another page, everything is retained in memory because the PropertyChanged event is still linked

      _my_Vm_PropertyChanged += PropertyChanged

There is no OnDisappear or Unload method I can see

Do I have no choice but to move all my display logic to the ViewModel to which the parent page has binding context set?

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

1 answer

Sort by: Most helpful
  1. JarvanZhang 23,951 Reputation points
    2021-03-26T09:21:59.873+00:00

    when the user returns to another page, everything is retained in memory because the PropertyChanged event is still linked

    Hi, Journeyman42-5521. How did you set binding for the contentView in xaml? I tested a basic demo to test the function, it works fine. Could you post the related code to reproduce the issue?

    Here is the related code about my test, you could refer to:

    Custom contentView.xaml:

    <StackLayout>
        <Label Text="{Binding TheText}" HorizontalOptions="CenterAndExpand" />
    </StackLayout>
    

    Page1

    <StackLayout>
        <Button Text="Navigation" Clicked="Button_Clicked"/>
        <local:View1 />
    </StackLayout>
    
    public partial class Page1 : ContentPage
    {
        public string TheText { get; set; }
        public Page1()
        {
            InitializeComponent();
    
            TheText = "testing for the binding of contentView";
            BindingContext = this;
        }
    
        private void Button_Clicked(object sender, EventArgs e)
        {
            Navigation.PushAsync(new Page2());
        }
    }
    

    Page2

    <StackLayout>
        <local:View1 />
    </StackLayout>
    
    public partial class Page2 : ContentPage
    {
        public string TheText { get; set; }
        public Page2()
        {
            InitializeComponent();
    
            TheText = "the binding text in Page2.xaml.cs";
            BindingContext = this;
        }
    }