Click Event of NSStatusItem in Xamarin.Mac

This issue annoyed me a bit so I thought I’d share. I was working with an application that had a NSStatusItem (also known as a Menu Extra). This is the Windows equivalent of a system tray application. My goal was to show the status of my application in the top item of its context menu. I had a variable in a shared project that’s updated with a status. I struggled to find a way to bind this variable to the NSMenuItem in a slick way. Then it occurred to me that I could update it as the menu opens. I needed to find an event equivalent to opening/showing/expanding. I came across an example online using the Action property of the NSStatusItem. It is more like a Click or Activated event. So that’s what I used.

For some reason I struggled to get it to fire. I eventually came across this Apple documentation. It says setting the Menu property at runtime negates the Click event. So I had to find a way to assign the menu in a different way to keep the event in tact. Whatever I found must be dynamic.

I accomplished this with the PopUpStatusItemMenu method.
Variables explained:
  • statusItemNSStatusItem
  • menuAuthStatusNSMenuItem
  • menuAuthNSMenu
  • Client.TrayStatus – the string variable in a shared project
Now each time the icon is clicked the item text of the menu is immediately set to the shared variable. Then the menu is presented to the user in all its glory!

Read More