0

Could anyone tell me or point to a guide explaining how to create event handlers for Xamarin.Mac forms?

I simply cannot find how to do it when I open XCode Interface Editor from Xamarin Studio.

SushiHangover
  • 73,120
  • 10
  • 106
  • 165
user306080
  • 1,409
  • 3
  • 16
  • 37

2 Answers2

1

You are looking for what is called an Action in Cocoa.

There is a great tech article that takes you through the process of exposing an Action (and Outlets) in the Xcode Interface Editor so the 'event' is exposed via auto-generated (code-behind) C#:

https://developer.xamarin.com/guides/mac/user-interface/standard-controls/

A Simple example:

Create a Cocoa App via the Xamarin Studio template.

Double-click the Main.Storyboard entry in the solution explorer to open Xcode

Drag/Drop an NSButton onto your View (not the View Controller):

enter image description here

Highlight the NSButton and Ctrl-Drag/Drop it onto the ViewController.h (NOT the .m file):

enter image description here

Name it (MyButton for my example) and change the Connection from Outlet to Action.

Save the storyboard (Cmd-S) and flip back to Xamarin Studio (no need to close Xcode as you will be flipping back and forth a lot as you initially get up to speed.

In Xamarin, double click on the generated file ViewController.designer.cs and you will see your NSButton's partial class.

    [Action ("MyButton:")]
    partial void MyButton (Foundation.NSObject sender);
    

Double-click on the ViewController.cs file, click within the class but outside of other existing methods and start typing partial and you will get an Intellisense popup listing your Actions:

enter image description here

Hit enter and you have your first event created.

    partial void MyButton (NSObject sender)
    {
        throw new System.NotImplementedException ();
    }

Update the code to actually do something:

    partial void MyButton (NSObject sender)
    {
        (sender as NSButton).Title = "You clicked me";
    }

Compile/Run the app:

enter image description here

Click the button:

enter image description here

Community
  • 1
  • 1
SushiHangover
  • 73,120
  • 10
  • 106
  • 165
1

For a deeper understanding of Outlets and Actions, please see the Outlet and Action section of our Hello, Mac guide as well. I go into a bit more details of how they work in that doc.