为什么在 Xamarin 窗体中调用 Navigation.InsertPageBefore() 后导航对我不起作用?



我试图实现登录Xamarin表单(5.0.0,使用ActiveDirectory的内置登录页面)。关于如何使它工作有什么想法吗?

在App.xaml.cs的构造函数中,我有:

public App()
{
InitializeComponent();
MainPage = new NavigationPage(new LoginPage());
}

我实现了带有视图模型的登录页面,在其中我传递了一个回调,它应该(根据文档)将我的导航根设置为我的主页:

public partial class LoginPage : ContentPage
{
private async Task _handleLoginAsync()
{
Navigation.InsertPageBefore(new HomePage(), this);
await Navigation.PopAsync();
}
public LoginPage()
{
InitializeComponent();
BindingContext = new LoginPageViewModel(_handleLoginAsync);
}
}

在视图模型中,我尝试使用Device登录。BeginInvokeOnMainThread,调用我的(注意,为了简洁/整洁,我没有包括登录逻辑)

public Command LoginCommand => new Command(LoginUsingAzureAsync);
private Func<Task>_handleLoginAsync;
public LoginPageViewModel(Func<Task> handleLoginAsync)
{
_handleLoginAsync = handleLoginAsync;
LoginCommand.Execute(null);
}
internal void LoginUsingAzureAsync()
{
Device.BeginInvokeOnMainThread(async () =>
{
try
{
if (await Login()) == true)
{
UserDialogs.Instance.HideLoading();
await _handleLoginAsync();
return;
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
UserDialogs.Instance.Alert("The login has failed.");
}
});
}

它成功进入主页,但之后导航到其他页面不工作。当我调用下面的代码时,它会进入OtherPage()构造函数,但无法呈现新页面。

Navigation.PushAsync(new OtherPage());

注意,如果我使用PushAsync(new HomePage())而不是删除登录,则导航工作如预期的那样,但我更愿意从导航堆栈中删除登录页面。

提前感谢!


Update:这是初始HomeViewModel:

public class HomeViewModel
{
private readonly INavigation _navigation;
public Command GoToOtherPageCommand => new Command(GoToOtherPage);
public async void GoToOtherPage()
{
await App.Navigation.PushAsync(new OtherPage());
}
}

问题不在于登录,而在于homeepageviewmodel,它最初引用的是App.Navigation(见有问题的更新)。

将导航传递到我的ViewModel中就可以了:

public class HomeViewModel
{
private readonly INavigation _navigation;
public Command GoToOtherPageCommand => new Command(GoToOtherPage);
public async void GoToOtherPage()
{
await _navigation.PushAsync(new OtherPage());
}
public HomeViewModel(INavigation navigation)
{
_navigation = navigation;
}
}
public partial class HomePage : ContentPage
{
public HomePage()
{
InitializeComponent();
BindingContext = new HomeViewModel(Navigation);
}
}

最新更新