Search code examples
navigationmaui

Maui How to close modal page?


From a page I call a modal page. In the modal page is a form and two button "cancel" and "submit". After clicking one button the modal should close and the previous page should be visible.

How I have to handle the modal page click event to close the modal page?

(Or what is the standard way to close a modal page?

My page codebehind:

private async void Btn7_Clicked(object sender, EventArgs e)
{
    await Navigation.PushModalAsync(new ModalPage());
}

My ModalPage.xaml:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="Mandatos.Views.ModalPage"
         Title="ModalPage">
<VerticalStackLayout Margin="50">
    <Label Text="Example form" FontSize="30" HorizontalTextAlignment="Center" />
    <Grid WidthRequest="600" Margin="0, 30">
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="20" />
            <ColumnDefinition Width="3*" />
        </Grid.ColumnDefinitions>

        <Label Text="Input 1:" VerticalTextAlignment="End"/>
        <Entry Grid.Column="2" />

        <Label Grid.Row="1" Text="Input 2:" VerticalTextAlignment="End"/>
        <Entry Grid.Row="1" Grid.Column="2" />

        <Label Grid.Row="2" Text="Input 3:" VerticalTextAlignment="End"/>
        <Entry  Grid.Row="2" Grid.Column="2"/>

        <Label Grid.Row="3" Text="Input 4:" VerticalTextAlignment="End"/>
        <Entry  Grid.Row="3" Grid.Column="2" />

    </Grid>

    <Grid WidthRequest="600" >
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Button Text="Cancel"/>
        <Button Grid.Column="1" Text="Submit"/>
    </Grid>

</VerticalStackLayout>

ModalPage codebehind:

public partial class ModalPage : ContentPage
{
 public ModalPage()
 {
    InitializeComponent();
 }

 private void CancelButton_OnClicked(object sender, EventArgs e)
 {   //...???  }

 private void SubmitButton_OnClicked(object sender, EventArgs e)
 {   //...???  }
}

Solution

  • The answer on the modal page is:

    await Navigation.PopModalAsync();
    

    at my example:

    private async void CancelButton_OnClicked(object sender, EventArgs e)
    {
        await Navigation.PopModalAsync();
    }
    
    private async void SubmitButton_OnClicked(object sender, EventArgs e)
    {
        await Navigation.PopModalAsync();
    }
    

    I found the answer here: learn.microsoft.com/en-us/xamarin...