Treeview to Diagram Twoway

I am displaying the same data into both a TreeView and a GoDiagram. When selecting an item in the TreeView, I would like the corresponding node in the Diagram to be selected. And when I select a node in the Diagram, I would like the item in the Treeview to be selected. It is not clear how to do that using XAML binding mechanisms. I could not find anything similar in the provided examples or in the documentation. Am I missing it?

You can get it to work partly, but not completely, using only data binding.

However, you might need to deal with multiple selection and visibility issues, which may require more smarts than data binding can offer.

The following SelectionChanged event handlers work to sync up the selection of a ListBox and a Diagram:

[code] private void myListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) {
var lb = (ListBox)sender;
foreach (Object data in e.RemovedItems) {
Node node = myDiagram.PartManager.FindNodeForData(data, myDiagram.Model);
if (node != null) node.IsSelected = false;
}
foreach (Object data in e.AddedItems) {
Node node = myDiagram.PartManager.FindNodeForData(data, myDiagram.Model);
if (node != null) node.IsSelected = true;
}
}

private void myDiagram_SelectionChanged(object sender, SelectionChangedEventArgs e) {
  var dia = (Diagram)sender;
  foreach (Part part in e.RemovedItems) {
    myListBox.SelectedItems.Remove(part.Data);
  }
  foreach (Part part in e.AddedItems) {
    myListBox.SelectedItems.Add(part.Data);
  }
}[/code]

Note that the Diagram.SelectionChanged event is new for version 1.1. In version 1.0 you would need to put the event handler on the Diagram.SelectedParts collection rather than directly on the Diagram.

Hi Walter,

Indeed, multiple selection and visibility issues come up with data binding.

With code, if SelectedItems are added from the Listbox, nodes show up adorned in the diagram, as specified in the diagram data template. If SelectedItems are added from the diagram, they show up with a slightly different shade of gray in the ListBox. I suppose that can be changed also with a proper spec in the listbox data template.

In case both nodes and links are selected in the diagram, I assume we need to cast the parts to proper type node or link to select corresponding items in the listbox. Or is there a way to get only nodes or only links that are affected by the diagram selection?

Thanks a lot for your response,

You can get a collection of all of the selected nodes with:

myDiagram.SelectedParts.OfType()

or the corresponding node data:

myDiagram.SelectedParts.OfType().Select(n => n.Data)

Similarly, you can get the nodes in a Diagram.SelectionChanged event handler:

e.AddedItems.OfType()

Perfect.

Thanks