maui.net-mauimaui-blazor

MAUI Blazor access methods of host page (MainPage.xaml)


Digging into MAUI Blazor and trying to see if its possible to call methods of the host page of the BlazorWebView. (Like MainPage.xaml.cs)

We can call App.Current.MainPage.DisplayAlert so would it be possible to call something like App.Current.MainPage.MyMethod?

however creating a public method in the MainPage does not expose it like highlighted above.

I understand I can create a class and reference, but in this particular use case scenario I need to see if the above is possible. So far have found no documentation on it.


Solution

  • This has worked for me. In your main page:

    //MainPage.xaml.cs
    namespace Foo
    {
        public partial class MainPage : ContentPage
        {
            public MainPage()
            {
                InitializeComponent();
            }
            
            //this is the method I want to make available
            public string Bar()
            {
                return "Hell O'World"
            }
        }
    }
    

    Then, wherever you want to access the Bar method:

    //Utils.cs
    namespace Foo
    {
        public static class Utils
        {
            public static void GetFoo()
            {
                var mainpage = Application.Current.MainPage as MainPage;
                var results = mainpage?.Bar() ?? "Failed";
                Debug.WriteLine(results);
            }
        }
    }