Is there an event or method that is called after a NSCollectionViewItem is created to get or set the view controller?

89 Views Asked by At

I want to get a reference to the main applications view controller from inside of NSCollectionViewItem.

I created this function:

public partial class MyViewItemController : NSCollectionViewItem {

    private ViewController controller;

    // Called when created from unmanaged code
    public MyViewItemController(IntPtr handle) : base(handle) {
        Initialize();
    }

    partial void buttonAction(Foundation.NSObject sender) {
        var button = sender as NSButton;
        controller.performSomething(model);
    }

    private ViewController getController() {
        var localDelegate = CollectionView.Delegate as CollectionViewDelegate;
        var controller = localDelegate.ParentViewController as ViewController;
        return controller;
    }
}

But if I call it in the Initialize method it throws an error:

    private ViewController controller;

    // Shared initialization code
    void Initialize() {
        controller = getController();// Failed to lookup the required marshalling information.
    }

From the error it seems it is too early in the application life cycle to work.

Is there anyway I can get the view controller in the View Item class another way or any other method I can override instead of Initialize() where I can set the controller variable?

1

There are 1 best solutions below

1
Ol Sen On

You should be able to ask your view for its window and from there asking for the mainWindow

NSWindow *mainWindow = self.window.mainWindow;
//mainWindow.windowController
//mainWindow.contentViewController

you may have to check what class the controllers are for your use case.