简体   繁体   English

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

[英]How to access a MainWindow variable from a page in C# WPF?

I am trying to code a WPF desktop Application.我正在尝试编写 WPF 桌面应用程序。 Currently i have a Main Window (MainWindow) and a page (Pageone) under the same solution.目前我在同一解决方案下有一个主要的 Window (MainWindow)和一个页面(Pageone) From my MainWindow.xaml.cs page, i have a variable (proc1) which i want to pass to my Pageone.xaml.cs page and maybe even more pages in the future to access and use for some calculation.在我的MainWindow.xaml.cs页面中,我有一个变量(proc1) ,我想将它传递给我的Pageone.xaml.cs页面,将来可能还会有更多页面来访问和用于某些计算。

However i cant seem to find a method to successfully do this, i have tried making my variable "public" , and instantiate the MainWindow object for my page to access it but it doesn't seem to work.但是我似乎找不到成功执行此操作的方法,我尝试将变量设为“public” ,并为我的页面实例化MainWindow object 以访问它,但它似乎不起作用。 (A field initializer cannot reference the non-static field, method, or property 'Pageone.pog')

MainWindow.xaml.cs主窗口.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 Pageone.xaml.cs

    public partial class Pageone : Page
    {

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

     ...

I've heard that i will maybe need to use something called the MVVM or code a parameterized constructor but i'm not sure if its related to the code i'm doing.我听说我可能需要使用称为 MVVM 的东西或编写参数化构造函数,但我不确定它是否与我正在执行的代码有关。 Is there a better way to go about coding this?有没有更好的方法来 go 关于编码这个? Thanks.谢谢。

It can be done like:可以这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM