首页 > 解决方案 > MainWindows 和页面之间的导航错误(WPF 应用程序)

问题描述

我目前正在编写一个 wpf 应用程序,该应用程序允许用户首先选择当前在本地系统上运行的进程,单击按钮后,用户选择的内容将被传递到变量中,然后进入他们需要的接下来的几个页面回答并在文本框中输入信息,这些信息也需要保存在变量中。

我需要将所有这些信息存储在我最终编译的页面中,我将在文本框中显示所有这些信息。但是,我在尝试浏览这些页面/窗口时遇到了一些例外情况。

Mainwindow.xaml.cs(窗口)

private void startTroubleshootButton_Clicknew(object sender, RoutedEventArgs e)
        {

            //get the selected process at column/index 0 and store it in a variable,
            var selectedProcess = listViewProcesses.SelectedItems[0] as myProcess;
            //var selectedProcess1 = listViewProcesses.SelectedItems[2] as myProcess;
            if (selectedProcess == null)
            {
                MessageBox.Show("no selection made");
                return;
            }

            //Store the associated process name and PID in proc1 and proc2 variable
            proc1 = selectedProcess.processName;
            proc2 = selectedProcess.processId;


            MessageBox.Show($"you have selected the {proc1} application {proc2} ");

            //instantiate the Pageone page

            Q1 pg1 = new Q1();
            this.Content = pg1;
        }

(Q1.xaml.xs (Page))点击compileButtonClick后收到错误

private void compileButtonClick(object sender, RoutedEventArgs e)
        {
            var window = (MainWindow)Application.Current.MainWindow;
            string procName = window.proc1;
            int subprocPid = window.proc2;
            string procPID = subprocPid.ToString();
            MessageBox.Show(procName + procPID);

            Compiledpage pg = new Compiledpage(); //this may not be required/efficient

            //Show Pageone in the current window
            this.Content = pg;

        }
System.InvalidOperationException: 'Page can have only Window or Frame as parent.'

(Q1.xaml.xs (Page))单击homeButtonClick后收到错误

    private void homeButtonClick(object sender, RoutedEventArgs e)
    {
        MainWindow main = new MainWindow();
        this.Content = main;

    }
System.InvalidOperationException: 'Window must be the root of the tree. Cannot add Window as a child of Visual.'

编译页面.xaml.cs

public partial class Compiledpage : Page
    {
        public Compiledpage() 
        {
            InitializeComponent();
        }

        private string remoteIp;

        public void Window_Loaded(object sender, RoutedEventArgs e)
        {



            //instantiate the MainWindow and assign it to the 'window' variable

            var window = (MainWindow)Application.Current.MainWindow;
            string procName = window.proc1;
            int subprocPid = window.proc2;
            string procPID = subprocPid.ToString();
            //MessageBox.Show(procPID);

           ...

有没有更好的方法可以为这种“跨窗口/页面导航和存储值”方法编码?我听说最好使用 UserControl,但我不确定为什么会这样。

标签: c#.netwpfvariablesnavigation

解决方案


推荐阅读