我基本上想要访问所有者窗口的方法,但是我得到了一个Null Reference Exception
现在看起来如何: 我有我的MainWindow公共WriteLine方法
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();
}
}
然后在PlotWindow类中,我试图用这些行调用WriteLine:
writeline("Drawing plot");
(Owner as MainWindow).WriteLine("Drawing plot");
正如您所看到的,我通过Owner属性调用它,并通过在PlotWindow中使用delegate writeline。 任何这些方法都给我一个System.NullReferenceException
我错过了什么?
答案 0 :(得分:1)
正如您在注释中所述,您从构造函数调用的方法中调用Owner
属性。这意味着您尝试访问尚未设置的值。
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();
考虑使用在显示窗口后发生的事件,例如Loaded事件