【问题标题】:UWP Open New Window in ClassUWP 在课堂上打开新窗口
【发布时间】:2020-12-20 09:11:10
【问题描述】:

我的项目页面太多了,想把这些页面的打开和关闭写在一个类里。但它不会打开新页面。

谢谢。

我的班级代码

class Class
{
    public static void GoToOpenPage1()
    {
        Frame OpenPage1 = new Frame();
        OpenPage1.Navigate(typeof(MainPage));
    }
}

按钮点击代码

private void button_Click(object sender, RoutedEventArgs e)
    {
        Class.GoToOpenPage1();
    }

【问题讨论】:

  • 我可以知道该应用程序在 Windows IoT Core 上运行吗?如果是,Windows IoT Core 仅支持单页 UWP 应用程序,它无法像在 Windows 桌面上那样打开新页面。

标签: uwp windows-10-iot-core new-window openpages


【解决方案1】:

创建Frame后,需要将其插入到当前的可视化树中,这样才能“看到”。

例如,我们在MainPage.xaml中创建一个Grid。

<Grid x:Name="FrameContainer"  x:FieldModifier="public">

</Grid>

MainPage.xaml.cs中,我们可以通过静态变量暴露MainPage实例。

public static MainPage Current;
public MainPage()
{
    this.InitializeComponent();
    Current = this;
}

这样,当MainPage被加载时,FrameContainer也会被加载。我们可以通过MainPage.Current.FrameContainer外部获取这个Grid,然后将我们生成的Frame插入到这个Grid中,这样就完成了插入可视化树的步骤。

public static void GoToOpenPage1()
{
    Frame OpenPage1 = new Frame();
    OpenPage1.Navigate(typeof(OtherPage));
    MainPage.Current.FrameContainer.Children.Clear();
    MainPage.Current.FrameContainer.Children.Add(OpenPage1);
}

但从您提供的代码来看,您似乎正在导航到MainPage。如果需要让MainPage再次成为Window的内容,可以这样写:

var rootFrame = Window.Current.Content as Frame;
rootFrame.Navigate(typeof(MainPage));

以上内容属于页面导航,如果要打开新窗口,可以参考这个文档,里面有详细的说明:

【讨论】:

    【解决方案2】:

    如果您面向 Windows 10 版本 1903 (SDK 18362) 或更高版本,您可以使用 AppWindow API 打开一个窗口:

    class Class
    {
        public static async Task GoToOpenPage1()
        {
            AppWindow appWindow = await AppWindow.TryCreateAsync();
            Frame OpenPage1 = new Frame();
            OpenPage1.Navigate(typeof(MainPage));
            ElementCompositionPreview.SetAppWindowContent(appWindow, OpenPage1);
            await appWindow.TryShowAsync();
        }
    }
    

    在早期版本中,您应该创建一个CoreApplicationView

    class Class
    {
        public static async Task GoToOpenPage1()
        {
            CoreApplicationView newView = CoreApplication.CreateNewView();
            int newViewId = 0;
            await newView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                Frame OpenPage1 = new Frame();
                OpenPage1.Navigate(typeof(MainPage));
                Window.Current.Content = OpenPage1;
                Window.Current.Activate();
                newViewId = ApplicationView.GetForCurrentView().Id;
            });
            bool viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(newViewId);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-24
      • 1970-01-01
      相关资源
      最近更新 更多