1

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.

0

1 Answer 1

7

It can be done like:

var window = (MainWindow)Application.Current.MainWindow;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.