Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to implement an on loaded event for a content view in xamarin

Tags:

c#

xamarin

There doesn't seem to be an on loaded event for the content view and I can't seem to find a way to override the on appearing method either. Is there a way to implement on loaded.

like image 879
mpalmer Avatar asked Dec 19 '25 02:12

mpalmer


1 Answers

Unfortunately, at the moment this is not possible.

There's a feature request in Github issues asking for this. You can follow it here https://github.com/xamarin/Xamarin.Forms/issues/3486 and here https://github.com/xamarin/Xamarin.Forms/issues/2210.

In the meantime, you can make (a quite dirty hack) two public methods and call these from your OnAppearing() / OnDissapearing() Page callbacks.

<local:MyContentView x:Name="MyContentView" HeightRequest="100" WidthRequest="100">            
</local:MyContentView>

Code-behind on Page

protected override void OnAppearing()
{
    base.OnAppearing();
    (MyContentView as MyContentView)?.PageAppearing();
}

protected override void OnDisappearing()
{
    base.OnDisappearing();
    (MyContentView as MyContentView)?.PageDisappearing();
}

Your ContentView:

public partial class MyContentView : ContentView
{
    public MyContentView()
    {
        InitializeComponent();
    }

    public void PageAppearing()
    {
    }

    public void PageDisappearing()
    { 
    }
}

Note: If you are doing this for many ContentView there might be an improvement to this code like using an Interface that your ContentViews will implement and use that one to do the casting from the Page.

Hope this gives you an idea.

like image 183
pinedax Avatar answered Dec 21 '25 20:12

pinedax



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!