Thursday, July 21, 2016

Customize context menu in Nevron Diagram

Scenario:

I had a requirement for preventing user to edit the “Composite Shape” elements (e.g. Text Primitives, Ports etc.). This restriction is required during the development for most of the cases because programs are using these shapes for some special purpose representation and these should not be altered by the use at run time to keep them consistent.

If user change these shapes then it will be hard to know that it has been modified this diagram is saved as XML string in some data store. If shape elements are used to identify the shape elements by name then it will break the program for being consistent for these shapes. See the below image, If the edited port name is used in program to  identity the center port then it will be distinguish the center  port in all of these ports.

clip_image002[5]_thumb[1]


Finally, it is required to remove some commands from the context menu of the shape in the diagram view for the user so that user will not able to modify the shape elements.

Solution:

At first place, you need to use the “Protection” on the shape to prevent some operation. You can restrict few operation on the shape for the user.

clip_image003[9]_thumb[1]


These can be set programmatically, these are just for making restrictions on the shape not for the context menu operations. See below code example:
NAbilities shapeAbilities = new NAbilities();
shapeAbilities.All = false;
shapeAbilities.InplaceEdit = true;
shapeAbilities.ResizeX = true;
shapeAbilities.ResizeY = true;
shapeAbilities.Export = false;
NShape shape = (NShape)nDrawingDocument1.ActiveLayer.Children(null)[0];
shape.Protection = shapeAbilities;

Real Solution 
The simplest solution is that create a custom context menu builder for creating context menu for the current diagram view.  This will create/add the required command that you want to provide to the user while working in the diagram.
First create a Custom ContextMenuBuilder by inheriting “NDiagramContextMenuBuilder” class and override “BuildContextMenu” method. There you need to create the context menu and add the required commands to the created context menu.

internal class CustomContextMenuBuilder : NDiagramContextMenuBuilder
{
    public override NContextMenu BuildContextMenu(object obj)
    {
        NContextMenu contextMenu = new NContextMenu();
        contextMenu.Commands.Add(CreateCommand((int)DiagramCommand.Delete, false));

        return contextMenu;
    }
}
After that create an instance of this custom context menu builder and assign it to the ContextMenuBuilder property of your diagram command bars manager:
nDiagramCommandBarsManager1.ContextMenuBuilder = new CustomContextMenuBuilder();

No comments :

Post a Comment