views:

66

answers:

2

I have a form that looks a lot like Windows Explorer. On the left side I have a tree view control and on the right a regular panel. I want to have the ability to double click the splitter view to resize based on the width of the longest label in the tree view. Does anyone know of a good way of doing so?

My guess is that I would check each node and try to determine the length of each string. And then take that number and include any additional padding or margins. Regards.

+1  A: 

You can iterate through the list of nodes (using whatever criteria you decide - i.e., all nodes, just visible ones) and you should be able to compute the width for any particular node by doing something like this:

int theWidth = theTextWidth + theIndentSize * theIndentLevel + theImageWidth;

You could recursively walk the tree (again, skipping non-visible nodes if that is your implementation) and return theWidth from the call, comparing it to the previously computed maxWidth and that maxWidth should be pretty close to the width of the treeview (plus padding, margins, etc.). Then set the splitter's distance to that value.

itsmatt
+1  A: 

This worked:

    private static int GetNodeBounds(TreeNodeCollection nodes) {
        int w = 0;
        foreach (TreeNode node in nodes) {
            w = Math.Max(w, node.Bounds.Right);
            if (node.Nodes.Count > 0)
                w = Math.Max(w, GetNodeBounds(node.Nodes));
        }
        return w;
    }

Sample usage:

    treeView1.ClientSize = new Size(GetNodeBounds(treeView1.Nodes), treeView1.ClientSize.Height);

Beware that the value returned by GetNodeBounds() may change when the user expands nodes. It can only see the width of visible nodes.

Hans Passant