如何从C#WPF中的页面访问MainWindow变量?

Bongchi

我正在尝试编写WPF桌面应用程序。目前,我在相同的解决方案下有一个主窗口(MainWindow)和一个页面(Pageone)在我的MainWindow.xaml.cs页面中,我有一个变量(proc1),我想将其传递给Pageone.xaml.cs页面,将来甚至可能要访问更多页面,以进行一些计算。

但是,我似乎找不到能够成功执行此操作的方法,我尝试使变量“ public”并实例化MainWindow对象以供我的页面访问它,但它似乎不起作用。(A field initializer cannot reference the non-static field, method, or property 'Pageone.pog')

MainWindow.xaml.cs

public string proc1;

public void startTroubleshootButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var selectedProcess = listViewProcesses.SelectedItems[0] as myProcess;
                if (selectedProcess == null)
                {
                    MessageBox.Show("no selection made");
                    return;
                }

                proc1 = selectedProcess.processName;

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

                Pageone pg = new Pageone(this);
                this.Content = pg;


            }
            catch(ArgumentOutOfRangeException)
            {
                return;
            }
        }

Pageone.xaml.cs

    public partial class Pageone : Page
    {

        public Pageone(MainWindow mainWindow)
        {
            InitializeComponent();   
        }
        MainWindow pog = new MainWindow();
        string procName = pog.proc1;

     ...

我听说我可能需要使用MVVM或对参数化构造函数进行编码,但是我不确定它是否与我正在执行的代码有关。是否有更好的方法进行编码?谢谢。

内霍赖

可以这样完成:

var window = (MainWindow)Application.Current.MainWindow;

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章