Bongchi
Bongchi

Reputation: 47

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

I am trying to code a WPF desktop Application. Currently i have a Main Window (MainWindow) and a page (Pageone) under the same solution. 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.

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. (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;

     ...

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. Is there a better way to go about coding this? Thanks.

Upvotes: 1

Views: 4355

Answers (1)

Nehorai Elbaz
Nehorai Elbaz

Reputation: 2452

It can be done like:

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

Upvotes: 7

Related Questions