Category / Section
How to create port at runtime through set tool in WPF Diagram (SfDiagram)?
2 mins read
Automatic Port Creation
WPF Diagram (SfDiagram) provides an option to create a port dynamically by clicking and dragging the mouse over any node or connector. This can be achieved by using the combination of SetTool and ObjectDrawn event.
Enable Drawing in SetTool
This SetTool method will be invoked when mouse pointer is over on Diagramming Element.
Set Port for Intersection
The ObjectDrawn event will be invoked while drawing the objects. There are two properties in the argument of this event to set Source and Target port of the Connector.
C#
public class CustomDiagram:SfDiagram { public CustomDiagram() { (this.Info as IGraphInfo).ObjectDrawn += CustomDiagram_ObjectDrawn; } private void CustomDiagram_ObjectDrawn(object sender, ObjectDrawnEventArgs args) { //SourcePort should be set on Started state if (args.State == DragState.Started) { if (args.Item is IConnector) { IConnector connector = args.Item as IConnector; if (connector.SourceNode != null) { if ((connector.SourceNode as NodeViewModel).Ports == null) //Initialize the Port collection (connector.SourceNode as NodeViewModel).Ports = new ObservableCollection<IPort>(); //Set the TargetPort as NodePort to the Node args.SourcePort = new NodePortViewModel(); } if (connector.SourceConnector != null) { if ((connector.SourceConnector as ConnectorViewModel).Ports == null) //Initialize the Port collection (connector.SourceConnector as ConnectorViewModel).Ports = new ObservableCollection<IPort>(); //Set the TargetPort as ConnectorPort to the Connector args.SourcePort = new ConnectorPortViewModel(); } } } //TargetPort should be set on Started state if (args.State == DragState.Completed) { if (args.Item is IConnector) { IConnector connector = args.Item as IConnector; if (connector.TargetNode != null) { if ((connector.TargetNode as NodeViewModel).Ports == null) //Initialize the Port collection (connector.TargetNode as NodeViewModel).Ports = new ObservableCollection<IPort>(); //Set the TargetPort as NodePort to the Node args.TargetPort = new NodePortViewModel(); } if (connector.TargetConnector != null) { if ((connector.TargetConnector as ConnectorViewModel).Ports == null) //Initialize the Port collection (connector.TargetConnector as ConnectorViewModel).Ports = new ObservableCollection<IPort>(); //Set the TargetPort as ConnectorPort to the Connector args.TargetPort = new ConnectorPortViewModel(); } } } } //Override the SetTool method protected override void SetTool(SetToolArgs args) { if (args.Source is INode || args.Source is IConnector) { args.Action = ActiveTool.Draw; } else { base.SetTool(args); } } }