You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin UWP打开独立AppWindow后导航失效问题求助

解决Xamarin UWP多窗口导航失效问题

问题根源

你在新窗口的TheStandalonePage中调用LoadApplication(new COREAPP.App()),会创建第二个COREAPP.App实例,导致App.Current指向新窗口的App实例。此时原窗口中执行App.Current.MainPage = new AnotherPage();,实际修改的是新窗口的MainPage,而非原窗口的,所以原窗口看不到导航效果。

解决方案:复用Core App实例,避免重复初始化

不需要在新窗口中重新加载整个Application,直接在UWP的独立窗口页面中承载Core项目的页面即可:

1. 修改UWP项目的TheStandalonePage.xaml

添加FormsView控件作为Xamarin.Forms页面的容器:

<Page
    x:Class="YourUWPNamespace.TheStandalonePage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:forms="using:Xamarin.Forms.Platform.UWP"
    mc:Ignorable="d">

    <forms:FormsView x:Name="FormsHost" />
</Page>

2. 修改TheStandalonePage.xaml.cs

去掉重复的App初始化代码,直接将Core项目的MyStandAlonePage设置为FormsView的内容:

public TheStandalonePage()
{
    InitializeComponent();
    // 直接加载Core项目的独立页面,无需重新实例化App
    FormsHost.Content = new COREAPP.MyStandAlonePage();
    // 依赖注入已在原App启动时完成,无需重复调用MyDependencies.RegisterAll()
}

3. 调整OpenWindow依赖服务(可选优化)

确保窗口关闭时正确清理资源:

public class OpenWindow : IOpenWindow
{
    private AppWindow appWindow;
    private Frame appWindowFrame = new Frame();

    public async Task OpenSecondWindow()
    {
        if (appWindow == null)
        {
            appWindow = await AppWindow.TryCreateAsync();
            appWindow.Closed += (s, e) => 
            {
                // 清理FormsView内容,释放资源
                var standalonePage = appWindowFrame.Content as TheStandalonePage;
                standalonePage?.FormsHost.Content = null;
                
                appWindow = null;
                appWindowFrame.Content = null;
            };

            appWindowFrame.Navigate(typeof(TheStandalonePage));
            ElementCompositionPreview.SetAppWindowContent(appWindow, appWindowFrame);
        }

        await appWindow.TryShowAsync();
    }
}

验证效果

修改完成后,原窗口执行App.Current.MainPage = new AnotherPage();时,App.Current仍然指向原窗口的App实例,导航操作会正确作用于原窗口的页面,新窗口的独立页面也能正常运行。

内容的提问来源于stack exchange,提问作者Flaubert TAGU

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 05:23:12