Xamarin.Mac: Event Handlers

After running into several native crashes when using event handlers, I have been told that event handlers in MonoMac and Xamarin.Mac have never worked properly. So avoid using the bound event handlers and override the protocol methods instead, if available. If not, use target/action pairs. For instance if you want to handle the NSColorWell event when a color is selected, instead of using:

colorWell.Activated += (object sender, EventArgs e) => {
    //...
};

you should use a target/action since there is no delegate protocol for NSColorWell. Set an Action for it either in the XIB/Storyboard file or in code. If you set the action in the XIB/Storyboard and give it a name of colorWellValueChanged: then handle the event in this method:

[Action ("colorWellValueChanged:")]
void ColorWellValueChanged (Foundation.NSObject sender)
{
    //...
}

To set the target/action pair in code, use:

colorWell.Target = this;
colorWell.Action = new ObjCRuntime.Selector("colorWellValueChanged:");

So until events get bound properly in Xamarin.Mac, don’t use them. Use protocol delegates or target/action pairs instead.

Update: The even handlers appear to be fixed in an upcoming release of Xamarin.Mac. Should be in the next Alpha or Beta release.

Leave a Reply

Your email address will not be published. Required fields are marked *