NullReferenceException when accessing GUI Components in Controllers constructor

强颜欢笑 提交于 2019-12-12 15:12:44

问题


In Mono I have a simple NSWindow with Controller on it I drop a NSSplitView and a NSButton.

If I try to access the NSSplitView out of the Contstructor or Initialize() Method I get a nullReferenceException. Instead if I try to access the NSSplitView from a ButtonClicked Method, it works.

Well, it seems that the Framework creates the GUI Components after the controller's Construtor is called. But where should I put my code to configure GUI Components if not in the Constructor?

Thanks in advance. Johannes


回答1:


You should use the AwakeFromNib method in your controller class. It is called once all the objects have been loaded and properly connected.

public override void AwakeFromNib ()
{
    base.AwakeFromNib ();

    // Do something here with the outlets
}



回答2:


You should use

public override void ViewDidLoad() {
    base.ViewDidLoad();
}

for configuring your view because that's the method which is called when the view just loaded, not when you instantiated the controller. If you configure your view in AwakeFromNib() you'll force the instantiation of your view whereas you maybe don't need them now. Indeed, when you create a controller the view are not created until someone try to access viewController.View.



来源:https://stackoverflow.com/questions/13038438/nullreferenceexception-when-accessing-gui-components-in-controllers-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!