Search code examples
c#xamlblazormaui

How to Call Function Inside .xaml Page From A .blazor Page in MAUI


I want to call a function from a .xaml.cs file from within a .blazor page. The goal is to call it when a specific button is clicked, but I can't find any information on how to accomplish this; the most I've found is communicating from MainLayout.razor, which isn't helpful to me. Having the button be directly inserted into the .xaml file won't work either, because I need it to be inaccessible except under certain conditions determined inside the .blazor page. I tried Application.Current.MainPage, but sadly that does not allow me to reach the function. Any and all help is appreciated!

Ideally, the blazor code would look something like:

<button @onclick="ActivatesXAMLFunction">Activate .xaml Function</button>

@code {
    protected async Task ActivatesXAMLFunction()
    {
        var mainPage = Microsoft.Maui.Controls.Application.Current.MainPage as MainPage;
        if (mainPage == null){  }
        else
        {
            await mainPage.XAMLFunction();
        }
    }
}

which would trigger a function in the MainPage .xaml class:

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
    }
    public async Task XAMLFunction()
    {
        //XAMLFunction code
    }
}

App.xaml.cs code:

public partial class App : Application
{
    public App()
    {
        InitializeComponent();

        MainPage = new NavigationPage(new MainPage());
    }
}

Solution

  • I use Application.Current.MainPage and can access the function in XAML page.

    <button @onclick="ActivatesXAMLFunction">Activate .xaml Function</button>
    
    @code {
    public async Task ActivatesXAMLFunction()
    {
        NavigationPage mainpage = Application.Current.MainPage as NavigationPage;
        MainPage rootpage = mainpage.RootPage as MainPage;
        await rootpage.XAMLFunction();
    }
    

    And in MainPage code-behind,

        public MainPage()
        {
            InitializeComponent();
        }
    
        public async Task XAMLFunction()
        {
            Console.WriteLine("123");
        }
    }
    

    When clicking the Button, the XAMLFunction in MainPage can be invoked.