Reputation: 173
I basically want to access methods of owner window, but I get a Null Reference Exception
How does it look like now: I have my MainWindow with public WriteLine method
public partial class MainWindow : Window
{
public void WriteLine(string text, params object[] args)
{
text = String.Format(text, args);
outputBox.AppendText(text + "\r\n");
}
private void ShowPlot()
{
PlotWindow plotWindow = new PlotWindow();
plotWindow.writeline += WriteLine;
plotWindow.Owner = this;
plotWindow.Show();
}
}
Then in PlotWindow class I am trying to call WriteLine with these lines:
writeline("Drawing plot");
(Owner as MainWindow).WriteLine("Drawing plot");
As you can see, I'm calling it through Owner property and through using the delegate writeline in PlotWindow. Any of these approaches gives me a System.NullReferenceException
What am I missing?
Upvotes: 0
Views: 689
Reputation: 250106
As you state in the comments, you invoke the Owner
property from a method invoked by the constructor. This means you try to access values you have not set yet.
PlotWindow plotWindow = new PlotWindow(); // This is where you try to access the Owner, this is where the constructor is invoked
plotWindow.writeline += WriteLine;
plotWindow.Owner = this; // This is where you set the owner
plotWindow.Show();
Consider using an event that occurs after the window is shown, such as the Loaded event
Upvotes: 1