我觉得我只是没有向谷歌霸主问这个问题,所以我想看看是否有人可以帮助解释如何做到这一点。我有一个新的 .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
After button clicked
主页添加编辑
主页 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