[英]Accessing owner window methods in WPF
我基本上想訪問所有者窗口的方法,但是卻收到一個Null引用異常
現在的樣子:我的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中的委托writeline來調用它。 這些方法中的任何一種都給我System.NullReferenceException
我想念什么?
在注釋中聲明時,可以從構造函數調用的方法中調用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事件
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.