.Net Maui - 如何返回根页面

2023-12-03

我觉得我只是没有向谷歌霸主问这个问题,所以我想看看是否有人可以帮助解释如何做到这一点。我有一个新的 .Net Maui 应用程序,它使用 4 个不同的视图/页面。我创建的 MainPage(根)允许我从我们的数据库中搜索用户,然后将您转换到新页面;我将其称为“结果页面”。从那里,您可以选择一个用户并进入可以执行编辑的详细信息页面。进行编辑并保存后,它会将您发送到我的最终页面 (SuccessPage),其中包含有关更改的消息。

这一切就像一个魅力。我可以使用 ViewModels 和 QueryProperties 将数据传递到页面,并将更改保存到数据库。失败的地方在成功页面上。收到有关更新的消息后,我希望有一个按钮,用户可以直接返回主页并可以执行新的搜索并重复上述所有步骤。

对于所有其他页面转换,我可以利用Shell.Current.GoToAsync()进入新页面和/或传递数据,如下所示:

await Shell.Current.GoToAsync(nameof(ResultsPage));

or

await Shell.Current.GoToAsync($"{nameof(DetailsPage)}?Parameter={param}");

从成功页面,我尝试将await Shell.Current.GoToAsync(nameof(MainPage));,但这会抛出一个关于“当前不支持到 shell 元素的相对路由”的异常,并建议我尝试在我的 uri 中添加 /// 前缀。我尝试这样做,但唯一改变的是页面标题;它实际上并没有恢复 MainPage UI 元素。那么怎样才能让shell返回到MainPage呢?

另外,我也尝试过await Shell.Current.Navigation.PopToRootAsync();,但是遇到了同样的问题,就像我在 uri 前面加上斜杠一样;它更改标题但不更改任何 UI 元素

Edit

作为参考,这里是按钮背后的代码(注意:我留下了注释掉的尝试,并在它们旁边添加了注释,显示它们如何没有帮助

private async void ReturnSearchButton_Clicked(object sender, EventArgs e)
    {
        //await Shell.Current.GoToAsync("../"); //exception, ambiguous routes matched

        //List<Page> previousPages = Navigation.NavigationStack.ToList();
        //foreach (Page page in previousPages)
        //{
        //  Navigation.RemovePage(page); //exception, null value
        //}

        await Shell.Current.Navigation.PopToRootAsync();
    }

以下是单击按钮之前和之后的 UI 屏幕截图:

Before button clicked Before button press

After button clicked After button pressed

主页添加编辑

主页 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="UserNameReset.Views.MainPage"
             Title="Home">
    <VerticalStackLayout Padding="10"
                         Margin="5">

        <Label 
            Text="Reset Users"
            SemanticProperties.HeadingLevel="Level1"
            FontSize="32"
            HorizontalOptions="Center" />

        <Label
            Text="Enter the users email address or their ID with Pin" 
            SemanticProperties.HeadingLevel="Level3"
            HorizontalOptions="Center"
            FontSize="18"/>

        <Label
            x:Name="fullWarningLabel"
            SemanticProperties.HeadingLevel="Level3"
            HorizontalOptions="Center"
            FontSize="18"
            TextColor="Red"
            Text="You must provide either the users email OR their ID and pin"
            IsVisible="false"/>

        <Entry 
            x:Name="emailEntry"
            Placeholder="[email protected]"
            ClearButtonVisibility="WhileEditing"
            Completed="Entry_Completed"
            Keyboard="Email"
            IsSpellCheckEnabled="False"/>

        <Label
            Text="OR"
            SemanticProperties.HeadingLevel="Level3"
            HorizontalOptions="Center"
            FontSize="18"/>

        <Grid ColumnDefinitions="*,*" ColumnSpacing="4" RowDefinitions="*,*" RowSpacing="2">
            <Entry
                x:Name="idEntry"
                Placeholder="ID"
                ClearButtonVisibility="WhileEditing"
                Grid.Column="0"
                Completed="Entry_Completed"
                IsSpellCheckEnabled="False"/>
            <Label
                x:Name="idWarning"
                IsVisible="false"
                Text="Please enter the users ID"
                Grid.Column="0"
                Grid.Row="2"
                TextColor="Red"/>

            <Entry
                x:Name="pinEntry"
                Placeholder="PIN"
                ClearButtonVisibility="WhileEditing"
                Grid.Column="2"
                Completed="Entry_Completed"
                IsSpellCheckEnabled="False"/>
            <Label
                x:Name="pinWarning"
                IsVisible="false"
                Text="Please enter the users PIN"
                Grid.Column="2"
                Grid.Row="2"
                TextColor="Red"/>
        </Grid>

        <Button
            x:Name="SubmitButton"
            Text="Search"
            SemanticProperties.Hint="Click to search for the user by values you provided"
            Clicked="Entry_Completed"
            HorizontalOptions="Center"/>
    </VerticalStackLayout>
</ContentPage>

主页代码隐藏

using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using UserNameReset.Models;

namespace UserNameReset.Views;

public partial class MainPage : ContentPage
{
    readonly ILogger<MainPage> _logger;

    public MainPage(ILogger<MainPage> logger)
    {
        InitializeComponent();
        _logger = logger;
    }

    /// <summary>
    /// Triggered when the user clicks the "Search" button, 
    /// when they finish entering an email,
    /// or when they successfully enter both Id and Pin
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    public void Entry_Completed(object sender, EventArgs e)
    {
        _logger.LogInformation("Entry fields filled, checking values...");

        // Cleans up layout each time search is triggered
        pinWarning.IsVisible = false;
        idWarning.IsVisible = false;
        fullWarningLabel.IsVisible = false;

        bool validUser = false;
        bool usingPinAndId = false;
        Queried_User user = new();

        // Check that both the plant ID and PIN were provided
        if (!string.IsNullOrWhiteSpace(idEntry.Text) && !string.IsNullOrWhiteSpace(pinEntry.Text))
        {
            _logger.LogInformation("Pin and ID provided!");
            validUser = true;
            usingPinAndId = true;
            user.Pin = pinEntry.Text;
            user.Id = idEntry.Text;
        }
        // Check if the email was provided (only if the plant ID and PIN weren't)
        else if (!string.IsNullOrWhiteSpace(emailEntry.Text))
        {
            _logger.LogInformation("Email provided!");
            validUser = true;
            user.Email = emailEntry.Text;
        }
        // If nothing was provided, add a warning to the appropriate entry fields
        else
        {
            if (!string.IsNullOrWhiteSpace(plantIdEntry.Text))
                pinWarning.IsVisible = true;
            else if (!string.IsNullOrWhiteSpace(pinEntry.Text))
                idWarning.IsVisible = true;
            else
                fullWarningLabel.IsVisible = true;
        }

        // Did we get a valid user obj? Navigate to the results page if so
        if (validUser)
        {
            // create a message of how the search is proceeding, changing text depending on search method
            string msg = "Searching via " + (usingPinAndId ? "plant ID: (" + user.Id + ") and pin: (" + user.Pin + ")" : "email: (" + user.Email + ")");


            _logger.LogInformation("User info validated. Going to get results from DB. " + msg);
            GoToResults(msg, user);
        }

        // Useful for displaying alerts or messages to the end user!!
        //await Shell.Current.DisplayAlert("Error!", $"Undable to return records: {ex.Message}", "OK");
    }


    /// <summary>
    /// Takes a simple user object and then redirects the user to the results page, 
    /// passing the user object as a query property
    /// </summary>
    /// <param name="user"></param>
    private async void GoToResults(string srchMthd, Queried_User user)
    {
        _logger.LogInformation($"User properties - email:{user.Email} - pin:{user.Pin} - ID:{user.Id}");

        await Shell.Current.GoToAsync($"{nameof(ResultsPage)}?SearchMethod={srchMthd}",
            new Dictionary<string, object>
            {
                ["User"] = user
            });
    }
}

GitHub 更新

我创建了一个存储库,其中托管了重复此问题的应用程序的简化版本:GitHub

编辑2022-10-6

由于其他人的建议,我在 Maui GitHub 上针对这个问题开了一个新问题。要查看该问题并跟踪其进展,请转至here


我创建了一个新示例进行测试,并尝试使用await Shell.Current.Navigation.PopToRootAsync(); and await Shell.Current.GoToAsync($"//{nameof(MainPage)}");导航到根页面。两者都显示了主页的标题,但没有显示页面的内容。

于是我点击工具栏上的按钮查看实时可视化树,发现当我回到主页时,里面只有主页。然后我尝试在android平台上运行它,它运行正常。这应该是Windows平台上用户访问根页面时的显示错误。

您可以尝试在github上向maui举报。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

.Net Maui - 如何返回根页面 的相关文章

随机推荐