Synchronizing Scrolling WinForms TreeViews

In my previous post I sketched the mechanism to implement a TreeView class which raises scroll events and allows setting the scrollbar positions of a custom TreeView.

Now we need to wire up the events and the scroll methods of two TreeView controls.

First, each TreeNode object needs to know its corresponding TreeNode in the other TreeView for synchronization. We can use the Tag property to store the other TreeNode like this:

var tnL = tnLeftRoot.Nodes.Add("this is node " + i);
var tnR = tnRightRoot.Nodes.Add("this is node " + i);

tnL.Tag = tnR;
tnR.Tag = tnL;

Apart from the ScrollH/V messages, we also want to synchronize the Collapse and Expand actions. If one TreeNode is collapsed or expanded, its corresponding TreeNode in the other TreeView should perform the same action:

private void tvLeft_AfterCollapse(object sender, TreeViewEventArgs e)
{
    (e.Node.Tag as TreeNode).Collapse();
}

private void tvLeft_AfterExpand(object sender, TreeViewEventArgs e)
{
    (e.Node.Tag as TreeNode).Expand();
}

Let’s also synchronize the scroll position:

private void tvLeft_ScrollH(object sender, devio.Windows.Controls.ScrollEventArgs e)
{
    tvRight.ScrollToPositionH(e.ScrollInfo);
}

private void tvLeft_ScrollV(object sender, devio.Windows.Controls.ScrollEventArgs e)
{
    tvRight.ScrollToPositionV(e.ScrollInfo);
}

Of course, these events need to be implemented for the other TreeView (tvRight) as well.

The control library and a sample WinForms application is available for download at GitHub.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.