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

1

6

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.

Munson answered 8/8, 2022 at 14:38 Comment(5)
you have to cast App.Current.MainPage to the appropriate type of YOUR app in order to access any public methodsCalenture
@Calenture Don't see how that is possible with Blazor Hybrid. Care to share an example?Munson
I don't know about Blazor, but in general that's how it works in Xamarin Forms (and I believe in MAUI too). App.Current.MainPage is just a Page, you will need to cast it to the subclass that contains the methods you want to use.Calenture
To Clarify: This question boils down to "From Maui Blazor, how refer to classes within the Maui code"? I don't know the answer to that, but given namespace MyApp and page MyPage, if you were writing within the Maui code itself, the syntax would be ((MyPage)App.Current.MainPage).MyMethod or the full path ((MyApp.MyPage)App.Current.MainPage).MyMethod. But I don't know in Blazor how you get at the app namespace. Must be some way to "bridge" to host code. OR might need to define some Interface or some communication mechanism.Pandanus
Thanks @ToolmakerSteve, That is what I'm hoping to find, Info on "bridge" to host code Seeing that App.Current.MainPage.DisplayAlert works and reaches the host page. I've tried what you recommended already with no luck.Munson
S
1

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);
        }
    }
}
Swartz answered 11/8, 2023 at 16:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.