选择

Users normally select Parts manually by clicking on them and they deselect them by clicking in the background or pressing the Esc key. You can select parts programmatically by setting Part.isSelected.

Users can also drag in the background in order to select the Parts that are within a rectangular area, via the DragSelectingTool. Read more about that in the Introduction to Tools at DragSelectingTool.

The Diagram keeps a collection of selected parts, Diagram.selection. That collection is read-only -- the only way to select or deselect a Part is by setting its Part.isSelected property. You can limit how many parts are selected by setting Diagram.maxSelectionCount. Prevent all selection by the user by setting Diagram.allowSelect to false. Or prevent a particular Part from being selected by setting Part.selectable to false.

You can show that a part is selected by either or both of two general techniques: adding Adornments or changing the appearance of some of the elements in the visual tree of the selected Part.

选择装饰(样式)

默认选择Part时,显示一个选择装饰Adornment来显示所选部件. 节点的默认选择装饰就是一个围绕整个节点的蓝色矩形框。 如果不需要这样的装饰,可以设置 Part.selectionAdorned 为false.

  diagram.nodeTemplate =
    $(go.Node, "Vertical",
      // the location is the center of the Shape, not the center of the whole Node
      { locationSpot: go.Spot.Center, locationObjectName: "ICON" },
      new go.Binding("location", "loc", go.Point.parse),
      $(go.Shape,
        {
          name: "ICON",
          width: 40, height: 40,
          fill: "gray",
          portId: ""  // the port is this Shape, not the whole Node
        },
        new go.Binding("figure")),
      $(go.TextBlock,
        { margin: new go.Margin(5, 0, 0, 0) },
        new go.Binding("text", "key"))
    );

  var nodeDataArray = [
    { key: "Alpha", figure: "Club", loc: "0 0" },
    { key: "Beta", figure: "Spade", loc: "200 50" }
  ];
  var linkDataArray = [
    { from: "Alpha", to: "Beta" }
  ];
  diagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray);
  diagram.commandHandler.selectAll();

By default an Adornment will apply to the whole Node. What if you want attention to be drawn only to the main piece of a node? You can accomplish that by naming that object and setting Part.selectionObjectName to that name.

  diagram.nodeTemplate =
    $(go.Node, "Vertical",
      { selectionObjectName: "ICON" },  // added this property!
        // the location is the center of the Shape, not the center of the whole Node
      { locationSpot: go.Spot.Center, locationObjectName: "ICON" },
      new go.Binding("location", "loc", go.Point.parse),
      $(go.Shape,
        {
          name: "ICON",
          width: 40, height: 40,
          fill: "gray",
          portId: ""  // the port is this Shape, not the whole Node
        },
        new go.Binding("figure")),
      $(go.TextBlock,
        { margin: new go.Margin(5, 0, 0, 0) },
        new go.Binding("text", "key"))
    );

  var nodeDataArray = [
    { key: "Alpha", figure: "Club", loc: "0 0" },
    { key: "Beta", figure: "Spade", loc: "200 50" }
  ];
  var linkDataArray = [
    { from: "Alpha", to: "Beta" }
  ];
  diagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray);
  diagram.selectCollection(diagram.nodes);

Note how the Part.selectionObjectName property is similar to the Part.locationObjectName in helping to treat a node as if only one piece of it really mattered.

自定义选择装饰

If you do want a selection adornment but want something different than the standard one, you can customize it. Such customization can be done by setting the Part.selectionAdornmentTemplate. In this example, nodes get thick blue rounded rectangles surrounding the selected node, and links get thick blue lines following the selected link's path.

  diagram.nodeTemplate =
    $(go.Node, "Auto",
      new go.Binding("location", "loc", go.Point.parse),
      $(go.Shape, "RoundedRectangle", { fill: "lightgray" }),
      $(go.TextBlock,
        { margin: 5 },
        new go.Binding("text", "key")),
      {
        selectionAdornmentTemplate:
          $(go.Adornment, "Auto",
            $(go.Shape, "RoundedRectangle",
            { fill: null, stroke: "dodgerblue", strokeWidth: 8 }),
            $(go.Placeholder)
          )  // end Adornment
      }
    );

  diagram.linkTemplate =
    $(go.Link,
      $(go.Shape, { strokeWidth: 2 }),
      $(go.Shape, { toArrow: "Standard" }),
      {
        selectionAdornmentTemplate:
          $(go.Adornment,
            $(go.Shape,
              { isPanelMain: true, stroke: "dodgerblue", strokeWidth: 8 }),
            $(go.Shape,
              { toArrow: "Standard", fill: "dodgerblue", stroke: null, scale: 2.5 })
          )  // end Adornment
      }
    );

  var nodeDataArray = [
    { key: "Alpha", loc: "0 0" },
    { key: "Beta", loc: "200 50" }
  ];
  var linkDataArray = [
    { from: "Alpha", to: "Beta" }
  ];
  diagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray);
  diagram.commandHandler.selectAll();

Note that an Adornment is just a Part. Adornments for nodes must contain a Placeholder in their visual tree. The Placeholder gets positioned where the selected object is.

Adornments for links are assumed to be panels of Panel.type that is Panel,Link. Hence the main element may be a Shape that gets the geometry of the selected Link's path shape, and the other elements of the adornment may be positioned on or near the segments of the link route just as for a regular Link.

More Complex Adornments

The custom Adornment for a Node need not be only a simple Shape outlining the selected node. Here is an adornment that adds a button to the adornment which inserts a node and a link to that new node.

  function addNodeAndLink(e, b) {
    // take a button panel in an Adornment, get its Adornment, and then get its adorned Node
    var node = b.part.adornedPart;
    // we are modifying the model, so conduct a transaction
    var diagram = node.diagram;
    diagram.startTransaction("add node and link");
    // have the Model add the node data
    var newnode = { key: "N" };
    diagram.model.addNodeData(newnode);
    // locate the node initially where the parent node is
    diagram.findNodeForData(newnode).location = node.location;
    // and then add a link data connecting the original node with the new one
    var newlink = { from: node.data.key, to: newnode.key };
    diagram.model.addLinkData(newlink);
    // finish the transaction -- will automatically perform a layout
    diagram.commitTransaction("add node and link");
  }

  diagram.nodeTemplate =
    $(go.Node, "Auto",
      $(go.Shape, "RoundedRectangle", { fill: "lightgray" }),
      $(go.TextBlock,
        { margin: 5 },
        new go.Binding("text", "key")),
      {
        selectionAdornmentTemplate:
          $(go.Adornment, "Spot",
            $(go.Panel, "Auto",
              // this Adornment has a rectangular blue Shape around the selected node
              $(go.Shape, { fill: null, stroke: "dodgerblue", strokeWidth: 3 }),
              $(go.Placeholder)
            ),
            // and this Adornment has a Button to the right of the selected node
            $("Button",
              { alignment: go.Spot.Right, alignmentFocus: go.Spot.Left,
                click: addNodeAndLink },  // define click behavior for Button in Adornment
              $(go.TextBlock, "ADD",  // the Button content
                { font: "bold 6pt sans-serif" })
            )
          )  // end Adornment
      }
    );

  diagram.layout = $(go.TreeLayout);

  var nodeDataArray = [
    { key: "Alpha" },
    { key: "Beta" }
  ];
  var linkDataArray = [
    { from: "Alpha", to: "Beta" }
  ];
  diagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray);
  diagram.select(diagram.findNodeForKey("Beta"));

Select any node and click the "ADD" button. Note how the diagram is automatically laid out as a tree.

数据绑定

与所有Part一样,Adornment支持数据绑定。如果修饰后的部件具有数据绑定(即ifPart.data is non-null),该部分的所有修饰也将绑定到相同的数据对象。简单来说就是支持new go.Binding绑定属性
  diagram.nodeTemplate =
    $(go.Node, "Auto",
      new go.Binding("location", "loc", go.Point.parse),
      $(go.Shape, "RoundedRectangle", { fill: "lightgray", strokeWidth: 2 },
        new go.Binding("stroke", "color")),
      $(go.TextBlock,
        { margin: 5 },
        new go.Binding("text", "key")),
      {
        selectionAdornmentTemplate:
          $(go.Adornment, "Auto",
            $(go.Shape,
              { fill: null, stroke: "dodgerblue", strokeWidth: 6 },
              new go.Binding("stroke", "color")),
            $(go.Placeholder)
          )  // end Adornment
      }
    );

  var nodeDataArray = [
    { key: "Alpha", loc: "0 0", color: "blue" },
    { key: "Beta", loc: "200 50", color: "red" }
  ];
  var linkDataArray = [
    { from: "Alpha", to: "Beta" }
  ];
  diagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray);
  diagram.selectCollection(diagram.nodes);

请注意每个装饰品与所选节点的data.color具有相同的颜色。

选择外观变化

Adding a selection adornment is not the only way to indicate visually that a Part is selected. You can also modify the appearance of one or more objects in your Part.

One way to do this is with data binding. Here we data bind the Shape.fill to the Part.isSelected property with a converter function that converts the boolean value to a color string or brush. We also turn off the regular rectangular blue selection adornment.

  diagram.nodeTemplate =
    $(go.Node, "Auto",
      { selectionAdorned: false },  // 禁用选择装饰adornment
      new go.Binding("location", "loc", go.Point.parse),
      $(go.Shape, "RoundedRectangle", { fill: "lightgray", strokeWidth: 2 },
        // when this Part.isSelected changes value, change this Shape.fill value:
        new go.Binding("fill", "isSelected", function(sel) {
          if (sel) return "cyan"; else return "lightgray";
        }).ofObject("")),  // The object named "" is the root visual element, the Node itself
      $(go.TextBlock,
        { margin: 5 },
        new go.Binding("text", "key"))
    );

  var nodeDataArray = [
    { key: "Alpha", loc: "0 0" },
    { key: "Beta", loc: "200 50" }
  ];
  var linkDataArray = [
    { from: "Alpha", to: "Beta" }
  ];
  diagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray);
  diagram.select(diagram.findNodeForKey("Beta"));

现在,当您选择节点时,其背景颜色将更改为青色.

更常用的方式是通过selectionChanged来监听Part.isSelected的选择改变事件,从而修改样式; 通常选择节点并改变或选中关联线的样式,都在此部分添加代码; 在这个例子中,我们将具有与前一个示例相同的作用。

  function onSelectionChanged(node) {
//选择改变事件的回调函数
    var icon = node.findObject("Icon");
    if (icon !== null) {
            //判断node的选择状态
      if (node.isSelected)
        icon.fill = "cyan";
      else
        icon.fill = "lightgray";
    }
  }

  diagram.nodeTemplate =
    $(go.Node, "Auto",
      { selectionAdorned: false,  // don't bother with any selection adornment
        selectionChanged: onSelectionChanged },  // 在 Part.isSelected 改变后调用
      new go.Binding("location", "loc", go.Point.parse),
      $(go.Shape, "RoundedRectangle",
        { name: "Icon", fill: "lightgray", strokeWidth: 2 }),
      $(go.TextBlock,
        { margin: 5 },
        new go.Binding("text", "key"))
    );

  var nodeDataArray = [
    { key: "Alpha", loc: "0 0" },
    { key: "Beta", loc: "200 50" }
  ];
  var linkDataArray = [
    { from: "Alpha", to: "Beta" }
  ];
  diagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray);
  diagram.select(diagram.findNodeForKey("Beta"));

There are some restrictions on what you can do in such an event handler: you should not select or deselect any parts, and you should not add or remove any parts from the diagram.

加入 GoJS 交流群
GoJS 交流群 (769862113)