How do I get the current mail item from Outlook ribbon context menu

Keith picture Keith · Jul 28, 2011 · Viewed 18.1k times · Source

I am creating an Outlook 2010 add-in and have added a context menu to my ribbon for idMso="contextMenuMailItem". On click, I would like to remove a category but in the click event handler, when I cast ctl.Context to MailItem, it's always null.

public bool btnRemoveCategory_IsVisible(Office.IRibbonControl ctl)
{
    MailItem item = ctl.Context as MailItem; //Always null
    if (item != null)
        return (item != null && HasMyCategory(item));
    else
        return false;
}

Does anyone know what's going on here? Thanks!

Answer

tcoolspy picture tcoolspy · Jul 28, 2011

The following link might provide you with some insight:

http://msdn.microsoft.com/en-us/library/ff863278.aspx

The "context" of the control gives you the corresponding Outlook object that you are customizing (for example an Inspector object). From there you'll need to reference the context object's CurrentItem property to get the MailItem.

For example,

public bool btnRemoveCategory_IsVisible(Office.IRibbonControl ctl)
{
    var item = ctl.Context as Inspector;
    var mailItem = item.CurrentItem as MailItem;
    if (item != null)
        return (item != null && HasMyCategory(item));
    else
        return false;
}

Hopefully, this helps.