Data Binding

Data binding is a way to extract a value from a source object and set a property on a target object. The target objects are normally GraphObjects; the source objects are usually data objects held in a model.

You could write code that gets a desired value from the model data, searches the Diagram for the appropriate Part, searches for the target GraphObject within the visual tree of that Part, and then sets one or more properties on that GraphObject with that value, perhaps after modifying or converting the original value in a way appropriate for the individual properties. However data binding offers a declarative way to specify such behavior just by supplying a Binding that names the properties on the source object and on the target object.

Trying to bind a non-existent property of a GraphObject will probably result in a warning or error that you can see in the output window. Always check the output window for any kinds of potential exceptions that are normally suppressed by the binding system.

Data bindings are used to keep GraphObject properties in sync with their Part's data's properties. They are not used to establish or maintain relationships between Parts. Each kind of Model has its own methods for declaring the relationships between parts.

The Relationships of Parts and Data and Binding

First, look at a diagram that includes comments about the GraphObjects used to build some example nodes and links:

The two Nodes and one Link belong to the Diagram and are on the left side, with shadows. The TreeModel and the two data objects in its Model.NodeDataSource are on the right side, in gray.

Each Node and Link has a Panel.Data property that references the data object in the model. Thus it is easy, given a Node, to refer to all of the data properties that you have put on the data in the model. These references are drawn as gray links.

Each Node also has three Bindings, drawn with dashed green lines:

The use of templates and data binding greatly simplify the information that must be stored in model data, and allow great flexibility in representing nodes and links in various manners independent of the model data. But not all data properties need to be used in Bindings in the template.

Note that Bindings are not references from the data to any Part. The whole point of separating models from diagrams is to avoid references from data to Diagrams or Nodes or Links or Tools. The only references from diagram to model are the Diagram.Model property and each node or link's Panel.Data property.

Binding string and number properties

It is easy to data bind GraphObject properties to data properties. In this example we not only data bind TextBlock.Text and Shape.Fill in nodes to property values of node data, but for thicker colored lines we also bind Shape.Stroke and Shape.StrokeWidth in links to property values of link data.

All you need to do is add to the target GraphObject a new Binding that names the target property on the visual object and the source property on the data object. Of course the target property must be a settable property; some GraphObject properties are not settable. If you specify a target property name that does not exist you will get warning messages in the output window. If the source property value is null, the binding is not evaluated.


  myDiagram.NodeTemplate =
    new Node("Auto")
      .Add(
        new Shape("RoundedRectangle") { Fill = "white" }
          .Bind("Fill", "Color"),  // Shape.Fill = Data.Color
        new TextBlock() { Margin = 5 }
          .Bind("Text", "Key")  // TextBlock.Text = Data.Key
      );

  myDiagram.LinkTemplate =
    new Link()
      .Add(
        new Shape()
          .Bind("Stroke", "Color")  // Shape.Stroke = Data.Color
          .Bind("StrokeWidth", "Thick"),  // Shape.StrokeWidth = Data.Thick
        new Shape() { ToArrow = "OpenTriangle", Fill = null }
          .Bind("Stroke", "Color")  // Shape.Stroke = Data.Color
          .Bind("StrokeWidth", "Thick")  // Shape.StrokeWidth = Data.Thick
      );

  var nodeDataList = new List<NodeData> {
    new NodeData { Key = "Alpha", Color = "lightblue" },
    new NodeData { Key = "Beta", Color = "pink" }
  };
  var linkDataList = new List<LinkData> {
    new LinkData { From = "Alpha", To = "Beta", Color = "blue", Thick = 2 }
  };
  myDiagram.Model = new MyModel {
    NodeDataSource = nodeDataList,
    LinkDataSource = linkDataList
  };

Note that there are two bindings using the "Color" property of the source link data. There is one for each target Shape in the Link template; each binds the Shape.Stroke property.

Binding object properties such as Part.Location

You can also data bind properties that have values that are objects. For example it is common to data bind the Part.Location property.

The value of Part.Location is a Point, so in this example the data property must be a Point.


  myDiagram.NodeTemplate =
    new Node("Auto")
      .Bind("Location")  // get the Node.Location from the Data.Location value
      .Add(
        new Shape("RoundedRectangle") { Fill = "white" }
          .Bind("Fill", "Color"),
        new TextBlock() { Margin = 5 }
          .Bind("Text", "Key")
      );

  var nodeDataList = new List<NodeData> {
    // for each node specify the location using Point values
    new NodeData { Key = "Alpha", Color = "lightblue", Location = new Point(0, 0) },
    new NodeData { Key = "Beta", Color = "pink", Location = new Point(100, 50) }
  };
  var linkDataList = new List<LinkData> {
    new LinkData { From = "Alpha", To = "Beta" }
  };
  myDiagram.Model = new MyModel {
    NodeDataSource = nodeDataList,
    LinkDataSource = linkDataList
  };

For conciseness the rest of these examples make use of the default Diagram.LinkTemplate.

Conversion functions

But what if you want the data property value for the location to be something other than a Point? You can provide a conversion function that converts the actual data property value to the needed value type or format.

For situations like this example, the Point class includes a static function, Point.Parse, that you can use to convert a string into a Point object. It expects two numbers to be in the input string, representing the Point.X and Point.Y values. It returns a Point object with those values.

You can pass a conversion function as the third argument to the GraphObject.Bind method or the Binding constructor. In this case it is Point.Parse. This allows the location to be specified in the form of a string ("100 50") rather than as an expression that returns a Point. For data properties on model objects, you will often want to use strings as the representation of Points, Sizes, Rects, Margins, and Spots, rather than references to objects of those classes. Strings are easily read and written in JSON and XML. Trying to read/write classes of objects would take extra space and would require additional cooperation on the part of both the writer and the reader.


  myDiagram.NodeTemplate =
    new Node("Auto")
      .Bind("Location", "Loc", Point.Parse)  // convert string into a Point value
      .Add(
        new Shape("RoundedRectangle") { Fill = "white" }
          .Bind("Fill", "Color"),
        new TextBlock() { Margin = 5 }
          .Bind("Text", "Key")
      );

  var nodeDataList = new List<NodeData> {
    new NodeData { Key = "Alpha", Color = "lightblue", Loc = "0 0" },  // note string values for location
    new NodeData { Key = "Beta", Color = "pink", Loc = "100 50" }
  };
  var linkDataList = new List<LinkData> {
    new LinkData { From = "Alpha", To = "Beta" }
  };
  myDiagram.Model = new MyModel {
    NodeDataSource = nodeDataList,
    LinkDataSource = linkDataList
  };

Conversion functions can be named or anonymous functions. They take a data property value and return a value suitable for the property that is being set. They should not have any side-effects. They may get called any number of times in any order.

Here is an example that has several Shape properties data-bound to the same (nullable) boolean data property named "Highlight". Each conversion function takes the boolean value and returns the appropriate value for the property that is data-bound. This makes it trivial to control the appearance of each node from the data by setting the "Highlight" data property to be either false or true.


  myDiagram.NodeTemplate =
    new Node("Auto")
      .Bind("Location", "Loc", Point.Parse)
      .Add(
        new Shape("RoundedRectangle")
          // default values if the Data.Highlight is null
          { Fill = "yellow", Stroke = "orange", StrokeWidth = 2 }
          .Bind("Fill", "Highlight", h => (bool)h ? "pink" : "lightblue")
          .Bind("Stroke", "Highlight", h => (bool)h ? "red" : "blue")
          .Bind("StrokeWidth", "Highlight", h => (bool)h ? 3 : 1),
        new TextBlock() { Margin = 5 }
          .Bind("Text", "Key")
      );

  var nodeDataList = new List<NodeData> {
    new NodeData { Key = "Alpha", Loc = "0 0", Highlight = false },
    new NodeData { Key = "Beta", Loc = "100 50", Highlight = true },
    new NodeData { Key = "Gamma", Loc = "0 100" }  // Highlight property null: use defaults
  };
  var linkDataList = new List<LinkData> {
    new LinkData { From = "Alpha", To = "Beta" }
  };
  myDiagram.Model = new MyModel {
    NodeDataSource = nodeDataList,
    LinkDataSource = linkDataList
  };

Note that a conversion function can only return property values. You cannot return GraphObjects to replace objects in the visual tree of the Part. If you need to show different GraphObjects based on bound data, you can bind the GraphObject.Visible or the GraphObject.Opacity property. If you really want different visual structures you can use multiple templates (Template Maps).

Changing data values

The examples above all depend on the data bindings being evaluated when the Part has been created and its Panel.Data property is set to refer to the corresponding node or link data. These actions occur automatically when the Diagram creates diagram parts for the data in the model upon setting Diagram.Model.

However, GoDiagram cannot know when the data property of an arbitrary object has been modified. If you want to change some data object in a model and have the diagram be automatically updated, what you should do depends on the nature of the property that you are changing.

For most data properties, ones that the model does not treat specially but are data-bound, you can just call Model.Set. In this example we modify the value of "Highlight" on a node data object. For fun, this modification occurs about twice a second.


  myDiagram.NodeTemplate =
    new Node("Auto")
      { LocationSpot = Spot.Center }
      .Add(
        new Shape("RoundedRectangle")
          // default values if the Data.Highlight is null
          { Fill = "yellow", Stroke = "orange", StrokeWidth = 2 }
          .Bind("Fill", "Highlight", h => (bool)h ? "pink" : "lightblue")
          .Bind("Stroke", "Highlight", h => (bool)h ? "red" : "blue")
          .Bind("StrokeWidth", "Highlight", h => (bool)h ? 3 : 1),
        new TextBlock() { Margin = 5 }
          .Bind("Text", "Key")
      );

  var nodeDataList = new List<NodeData> {
    new NodeData { Key = "Alpha", Highlight = false }
  };
  myDiagram.Model = new MyModel {
    NodeDataSource = nodeDataList  // just one node, and no links
  };

  void flash() {
    // all model changes should happen in a transaction
    myDiagram.Model.Commit(m => {
      var data = m.NodeDataSource.First() as NodeData;  // get the first node data
      m.Set(data, "Highlight", !data.Highlight);
    }, "flash");
  }

  void loop() {
    Task.Delay(500).ContinueWith((t) => { flash(); loop(); });
  }

  loop();

Changing graph structure

Data binding is not used to establish relationships between parts. For data properties that a particular model knows about, such as "To" or "From" for link data in a GraphLinksModel, you must call the appropriate model methods in order to modify the data property. Modifying a data property directly without calling the appropriate model method may cause inconsistencies or undefined behavior.

For node data, the model methods are Model.SetCategoryForNodeData, Model.SetKeyForNodeData, GraphLinksModel.SetGroupKeyForNodeData, TreeModel.SetParentKeyForNodeData, and TreeModel.SetParentLinkCategoryForNodeData. For link data, the model methods are GraphLinksModel.SetCategoryForLinkData, GraphLinksModel.SetKeyForLinkData, GraphLinksModel.SetFromKeyForLinkData, GraphLinksModel.SetFromPortIdForLinkData, GraphLinksModel.SetToKeyForLinkData, GraphLinksModel.SetToPortIdForLinkData, and GraphLinksModel.SetLabelKeysForLinkData.

This example changes the "To" property of a link data, causing the link to connect to a different node. This example uses the default Link template, which does not have any data bindings. The change in the link relationship is accomplished by calling a model method, not via a data binding.


  myDiagram.NodeTemplate =
    new Node("Auto")
      { LocationSpot = Spot.Center }
      .Add(
        new Shape("RoundedRectangle")
          { Fill = "yellow", Stroke = "orange", StrokeWidth = 2 },
        new TextBlock() { Margin = 5 }
          .Bind("Text", "Key")
      );

  var nodeDataList = new List<NodeData> {
    new NodeData { Key = "Alpha" },
    new NodeData { Key = "Beta" },
    new NodeData { Key = "Gamma" }
  };
  var linkDataList = new List<LinkData> {
    new LinkData { From = "Alpha", To = "Beta" }
  };
  myDiagram.Model = new MyModel {
    NodeDataSource = nodeDataList,
    LinkDataSource = linkDataList
  };

  void switchTo() {
    // all model changes should happen in a transaction
    myDiagram.Model.Commit(m => {
      var model = m as MyModel;
      var data = model.LinkDataSource.First();  // get the first link data
      if (model.GetToKeyForLinkData(data) == "Beta")
        model.SetToKeyForLinkData(data, "Gamma");
      else
        model.SetToKeyForLinkData(data, "Beta");
    }, "reconnect link");
  }

  void loop() {
    Task.Delay(1000).ContinueWith((t) => { switchTo(); loop(); });
  }

  loop();

Binding to GraphObject sources

The binding source object need not be a plain data object held in the diagram's model. The source object may instead be a named GraphObject in the same Part. The source property must be a settable property of the class. The binding is evaluated when the property is set to a new value.

One common use of such a binding is to change the appearance of a Part when the Part.IsSelected. Call Binding.OfElement to cause the Binding to use the object whose GraphObject.Name is the given name. Use the empty string, "", or no argument, to refer to the whole Part itself. This is a convenience so that you do not need to name the whole Part. "OfElement" really means "of the GraphObject named ...", as found by Panel.FindElement when there is a string argument.

In the example below, the Shape.Fill is bound to the Part.IsSelected property. When the node is selected or de-selected, the Part.IsSelected property changes value, so the binding is evaluated. The conversion function gets a boolean value and returns the desired brush color to be used as the shape's fill. This example also turns off selection adornments, so that the only visual way to tell that a node is selected is by the shape's fill color.


  myDiagram.NodeTemplate =
    new Node("Auto")
      { SelectionAdorned = false }
      .Add(
        new Shape("RoundedRectangle")
          .Bind(new Binding("Fill", "IsSelected", sel => (bool)sel ? "dodgerblue" : "lightgray")
            .OfElement()),  // no name means bind to the whole Part
        new TextBlock() { Margin = 5 }
          .Bind("Text", "Descr")
      );

  var nodeDataList = new List<NodeData> {
    new NodeData { Descr = "Select me!" },
    new NodeData { Descr = "I turn blue when selected." }
  };
  myDiagram.Model = new MyModel {
    NodeDataSource = nodeDataList
  };

Caution: do not declare cycles of binding dependencies -- that will result in undefined behavior. GraphObject binding sources also require the Part to be bound to data (i.e. Panel.Data must be non-null). The property on the GraphObject must be settable, so it does not work on read-only properties such as ones that return computed values (e.g. Part.IsTopLevel) or enumerables (e.g. Node.LinksConnected).

Binding to the shared Model.SharedData source

The binding source object may be a third kind of source, besides the Panel.Data or some GraphObject within the panel. It can also be the object that is the shared Model.SharedData object. This permits binding of Node or Link element properties to shared properties in the model that will exist and may be modified even though no nodes or links exist in the model.

In the example below, the Shape.Fill is bound to the "Color" property on the Model.SharedData object. The changeColor function, when called, modifies the SharedData object by calling Model.Set.


  private void Setup() {
    myDiagram.NodeTemplate =
      new Node("Auto")
        .Add(
          new Shape("RoundedRectangle") { Fill = "white" }  // the default value if there is no SharedData.Color property
            .Bind(new Binding("Fill", "Color").OfModel()),  // meaning a property of Model.SharedData
          new TextBlock() { Margin = 5 }
            .Bind("Text")
        );

    var nodeDataList = new List<NodeData> {
      new NodeData { Text = "Alpha" },
      new NodeData { Text = "Beta" }
    };
    myDiagram.Model = new MyModel {
      SharedData = new SharedData { Color = "yellow" },  // start all nodes yellow
      NodeDataSource = nodeDataList
    };
  }

  ...

  private void ChangeColor(object sender, EventArgs e) {
    myDiagram.Model.Commit(m => {
      var shared = m.SharedData as SharedData;
      var oldcolor = shared.Color;
      var newcolor = oldcolor == "lightblue" ? "lightgreen" : "lightblue";
      m.Set(shared, "Color", newcolor);
    }, "change shared color");
  }

Two-way data binding

All of the bindings above only transfer values from the source data to target properties. But sometimes you would like to be able to transfer values from GraphObjects back to the model data, to keep the model data up-to-date with the diagram. This is possible by using a TwoWay Binding, which can pass values not only from source to target, but also from the target object back to the source data.


  private void Setup() {
    myDiagram.NodeTemplate =
      new Node("Auto") { LocationSpot = Spot.Center }
        .Bind(new Binding("Location").MakeTwoWay())  // TwoWay Binding
        .Add(
          new Shape("RoundedRectangle") {
            Fill = "lightblue", Stroke = "blue", StrokeWidth = 2
          },
          new TextBlock() { Margin = 5 }
            .Bind("Text", "Key")
        );

    var nodeDataList = new List<NodeData> {
      new NodeData { Key = "Alpha", Location = new Point(0, 0) }
    };
    myDiagram.Model = new MyModel {
      NodeDataSource = nodeDataList
    };
  }

  ...

  private void ShiftNode(object sender, EventArgs e) {
    // all model changes should happen in a transaction
    myDiagram.Commit(d => {
      var data = d.Model.NodeDataSource.First() as NodeData;  // get the first node data
      var node = d.FindNodeForData(data);   // find the corresponding Node
      var p = node.Location;
      p.X += 10;
      if (p.X > 200) p.X = 0;
      // changing the Node.Location also changes the data.Location property due to TwoWay binding
      node.Location = p;
      // show the updated location held by the "Location" property of the node data
      label2.Text = data.Location.ToString();
    }, "shift node");
  }

In this example, the TwoWay Binding on Part.Location will update the "Location" property of the node data that is the Node's Panel.Data.

Just as you can use a conversion function when going from source to target, you can supply a conversion function to GraphObject.Bind or Binding.MakeTwoWay for going from target to source. For example, to represent the location as a string in the model data instead of as a Point:


// storage representation of Points/Sizes/Rects/Margins/Spots as strings, not objects:
new Binding("Location", "Loc", Point.Parse, Point.Stringify)

However, you must not have a TwoWay binding on the data property that is the "Key" property. (That defaults to the name "Key" but is actually the value of Model.NodeKeyProperty or GraphLinksModel.LinkKeyProperty.) That property value must always be unique among all node or link data within the model and is known by the Model. A TwoWay binding might change the value, causing a multitude of problems. Similarly, the Part.Key property is read-only, to prevent accidental changes of the key value.

Reasons for TwoWay Bindings

The basic reason for using a TwoWay Binding on a settable property is to make sure that any changes to that property will be copied to the corresponding model data. By making sure that the Model is up-to-date, you can easily "save the diagram" just by saving the model and "loading a diagram" is just a matter of loading a model into memory and setting Diagram.Model. If you are careful to only hold JSON-serializable data in the model data, you can just use the Model.ToJson and Model.FromJson methods for converting a model to and from a textual representation.

Most bindings do not need to be TwoWay. For performance reasons you should not make a Binding be TwoWay unless you actually need to propagate changes back to the data. Most settable properties are only set on initialization and then never change.

Settable properties only change value when some code sets them. That code might be in code that you write as part of your app. Or it might be in a command (see Commands) or a tool (see Tools). Here is a list of properties for which a TwoWay Binding is plausible because one of the predefined commands or tools modify them:

You will not need to use a TwoWay binding on a property if the Tool that modifies it cannot run, or if the command that modifies it cannot be invoked. You probably will not need a TwoWay binding on any other properties unless you write code to modify them. And even then it is sometimes better to write the code to modify the model data directly by calling Model.Set, depending on a OneWay Binding to update the GraphObject property.

It is also possible to use TwoWay Bindings where the source is a GraphObject rather than model data. This is needed less frequently, when you do not want to have the state stored in the model, but you do want to synchronize properties of GraphObjects within the same Part. Use TwoWay Bindings sparingly.