Category / Section
How to customize the contextmenu in WPF Diagram (SfDiagram)?
3 mins read
WPF Diagram (SfDiagram) provides clipboard options (cut,copy,paste and selectall) as in-built context menu items and allows you to define the custom menu items. The DiagramMenu and DiagramMenuItem are view models for ContextMenu and MenuItem respectively. The action for the DiagramMenuItem can be assigned with Command and CommandParameter property.
//Initialize the new custom menu with delete functionalities DiagramMenuItem menu = new DiagramMenuItem() { // Defines the content of menu item Content = "Delete", // Defines the icon that appears in menu item - it accepts the image path. Icon = @"pack://application:,,,/Icons/delete.png", // Defines the action of menu item Command = (diagram.Info as IGraphInfo).Commands.Delete }; Diagram.Menu.MenuItems.Add(menu); //Here Diagram is the instance of SfDiagram.
Add submenu items
The Items property of the DiagramMenuItem will assist to add submenu for it.
//Initialize the new custom Menu with zoom functionalities DiagramMenuItem Zoom = new DiagramMenuItem() { Content = "Zoom", Icon = @"pack://application:,,,/Icons/zoom.jpg", }; //Intialize the sub-menu item for Zooming menu with ZoomIn command DiagramMenuItem zoomIn = new DiagramMenuItem() { // Defines the content of menu item Content = "ZoomIn", // Defines the icon that appears in menu item - it accepts the image path. Icon = @"pack://application:,,,/Icons/zoomin.png", // Defines the action of menu item Command = diagramInfo.Commands.Zoom, // Defines the parameter of the menu item CommandParameter = new ZoomPositionParameter() { ZoomFactor = 0.5, ZoomCommand = ZoomCommand.ZoomIn } }; //Intialize the sub-menu item for Zooming enu with ZoomOut command DiagramMenuItem zoomOut = new DiagramMenuItem() { Content = "ZoomOut", Icon = @"pack://application:,,,/Icons/zoomout.png", Command = diagramInfo.Commands.Zoom, CommandParameter = new ZoomPositionParameter() { ZoomFactor = 0.5, ZoomCommand = ZoomCommand.ZoomOut } }; Zoom.Items = new ObservableCollection<DiagramMenuItem>(); //Adding zooming menus into diagram menu as to add sub-menu items. Zoom.Items.Add(zoomIn); Zoom.Items.Add(zoomOut); //Adding zooming menu into diagram default menu. Diagram.Menu.MenuItems.Add(Zoom);