Using Context Menus - kaisu1986/ATF GitHub Wiki
Context menus display a list of commands, typically in response to mouse clicks on a control.
For WinForms, the ICommandService
interface provides this method to display a context menu for commands, given a collection of commands:
void RunContextMenu(IEnumerable<object> commandTags, Point screenPoint);
This section discusses how to get the command list and display it in a context menu.
The IContextMenuCommandProvider
interface contains the following method to collect commands appropriate for a context:
IEnumerable<object> GetCommands(object context, object target);
The parameter target
is the object clicked on, and context
is the context containing target
.
Thus any class implementing IContextMenuCommandProvider
can provide a collection of commands for a given context.
This example from StandardEditCommands
provides a list of commands, if the provided context is a selection and instancing context and thus appropriate for editing:
IEnumerable<object> IContextMenuCommandProvider.GetCommands(object context, object clicked)
{
ISelectionContext selectionContext = context.As<ISelectionContext>();
IInstancingContext instancingContext = context.As<IInstancingContext>();
if ((selectionContext != null) && (instancingContext != null))
{
return new object[]
{
StandardCommand.EditCut,
StandardCommand.EditCopy,
StandardCommand.EditPaste,
StandardCommand.EditDelete,
};
}
return EmptyEnumerable<object>.Instance;
}
The ControlHostService
for WinForms has the following import:
[ImportMany]
private IEnumerable<Lazy<IContextMenuCommandProvider>> m_contextMenuCommandProviders;
This allows the component to get a collection of objects on which it can call IContextMenuCommandProvider.GetCommands()
to get a list of commands appropriate to the context. A variety of components export IContextMenuCommandProvider
, including several that create standard commands, such as StandardEditCommands
shown previously and DefaultTabCommands
.
ControlHostService
for WinForms uses the collection contextMenuCommandProviders
it imported, as shown previously, to implement this method that displays a context menu in response to a right-click event:
private void dockPaneStrip_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
DockPaneStripBase dockPaneStrip = sender as DockPaneStripBase;
ControlInfo info = FindControlInfo(m_activeDockContent.Controls[0]);
IEnumerable<object> commands =
m_contextMenuCommandProviders.GetCommands(null, info);
Point screenPoint = dockPaneStrip.PointToScreen(new Point(e.X, e.Y));
m_commandService.RunContextMenu(commands, screenPoint);
}
}