Vitaly
Vitaly

Reputation: 83

Passing file name (string argument) from Child window to a non-static method of Parent window

From Parent window I need to open a file and fill up different tables and controls (belong to Parent window) using its content. The name of the file (string) is formed in Child window by DataGrid.SelectedItem

private void LoadResultsCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var row = pastTestResultsDataGrid.SelectedItem as DataRowView;

            if (row != null)
            {
                string fileName = row[0] + " " + row[1] + " " + row[2] + " " + row[3] + " " + row[4] + " " + 
                    ((DateTime)row[6]).ToShortDateString().Replace('/', '-') + " " + ((DateTime)row[7]).ToShortDateString().Replace('/', '-') + " .dat";
                MainWindow.LoadResults(fileName);
            }

        }

As you see in Parent (MainWindow) I had to use static method

public static void LoadResults(string fileName)
        {
            string fullFileName = @"C:\Users\Public\Documents\Test Data\" + fileName;
            var binFormat = new BinaryFormatter();
            var testData = new TestData();

            if (File.Exists(fullFileName))
            {
                using (Stream fStream = new FileStream(fullFileName, FileMode.Open))
                {
                    testData = (TestData) binFormat.Deserialize(fStream);
                }
            }    
            //here I am trying to load data from testData instance of TestData class into data 
            //tables or set Text property of a TextBox. Can't access them from a static method!
        }

I know that I shouldn't even try to access non-static members from a static method. I am just trying to explain my task. Is there any way in WPF (where class Window is defined in XAML) to access the instance of Parent window at runtime and than its methods? I don't mind to change total approach if there is more elegant and simpler solution.

Upvotes: 2

Views: 821

Answers (2)

Alexei Levenkov
Alexei Levenkov

Reputation: 100610

If you want your method static just pass all arguments you need to it. The other option is to make your LoadResults instance method instatead of static.

Upvotes: 0

Steve Danner
Steve Danner

Reputation: 22168

In the very simplest form, you could obtain a reference to the parent window via the Owner property and change your existing LoadResults method to be an instance method.

MainWindow parent = this.Owner as MainWindow;
parent.LoadResults(fileName);

Upvotes: 2

Related Questions