Handling Events in the SharePoint Ribbon

The SharePoint SDK contains a good bit of information on how the customize the ribbon. Adding / replacing / removing controls to / from the ribbon is pretty straightforward although you have to get hip to writing a lot of XML (big deal... you're a SharePoint developer so you're used to it)!

So once you've customized the ribbon and it's looking all nice and pretty. Now it is time to handle the events when someone clicks one of your changes. This is all done using a command model similar to what you may be familiar with in WPF & Silverlight 4. Basically you give a command (the work that needs to happen) a name. You also have the ability to set one other property: "can execute". This "can execute" property lets you tell the commanding framework when the command is and is not available. For instance, paste is disabled when nothing is on the clipboard.

While you define the UI in your ribbon customizations declaratively, the SharePoint ribbon gives developers two ways to handle the commands. While all commands are implemented in client-side script, they are implemented either declaratively (usually in the same Feature element manifest as the UI declarations) or purely in script.

The declarative option, implemented using a <CommandUIHandler> (MSDN: CommandUIHandler) element, is great for easy and quick components. Here's what a sample one looks like that opens a dialog and displays a notification message:

While implementing your commands this way is all fine and good, what you will quickly find out is the challenge that is presented when you have a lot of script in your business logic. It gets to be quite a pain to maintain and can become quite cumbersome.

The other option, which I think is a bit more powerful and flexible, is the page component. A page component is a 100% script implementation that is implemented independently from the UX customizations. Page components are a bit more complex than a simple screenshot so I'll dive into those in my next post.