14

I have a TreeView that allows users to select certain elements of hierarchical data by checking or un-checking each item's checkbox. Currently I disable the box on nodes that have children using the checkbox hiding technique from another question, like so:

☑ Node 1
☐ Node 2
• Node 3
  ☑ Node 3.1
  ☑ Node 3.2
• Node 4
  ☐ Node 4.1
  ☑ Node 4.2

But a better solution would be to use tri-state check boxes for the parent nodes, like this:

☑ Node 1
☐ Node 2
☑ Node 3
  ☑ Node 3.1
  ☑ Node 3.2
☒ Node 4
  ☐ Node 4.1
  ☑ Node 4.2

Since this functionality was available in Win32, my question is how to do this without drawing the boxes myself (e.g., as a user-drawn control or using an image list). I am not familiar with the Win32 API at all; how would one extend the technique linked above to enable tri-state checboxes on a managed TreeView control?

Community
  • 1
  • 1
Philip Hanson
  • 1,847
  • 2
  • 15
  • 24
  • Another question in this vein, but didn't show up in the dupe finder: http://stackoverflow.com/questions/3051339/three-state-treeview-windows-forms – Philip Hanson Apr 11 '11 at 19:18

3 Answers3

13

This code might help you if you are thinking of drawing the mixed checkbox

class MixedCheckBox:Control
{
    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        CheckBoxRenderer.DrawCheckBox(e.Graphics, new Point(0, 0), Bounds, 
            Text, Font, false, 
            System.Windows.Forms.VisualStyles.CheckBoxState.MixedNormal);
    }
}

This will render: enter image description here

Good luck!

Community
  • 1
  • 1
Homam
  • 23,263
  • 32
  • 111
  • 187
  • 1
    Using CheckBoxRenderer is a good tip -- the subclassing solutions I've seen use image lists. Obviously, images are not going to be as portable as calling the renderer directly. – Philip Hanson Apr 13 '11 at 13:46
  • 1
    And how does one would use it exactly with a `TreeView` control, as OP asked? – Deilan Oct 08 '20 at 20:09
11

There is now a neat looking solution at Code Project, Tri-State Tree View

I'm just researching at the moment, so haven't yet used it.

PaulA
  • 111
  • 1
  • 3
2

Have you taken a look at this? It seems to do the job. It might be a bit dated, (looks like the article is from 2004), but I'm sure the same principles can be extended to whatever you need to do.

merthsoft
  • 878
  • 1
  • 7
  • 10
  • Hmm... I happened across that, but thought it was license-encumbered for some reason. There's a copyright notice at the top. On closer inspection, though, it may be under LGPL. Will leave the question open for a while to see if there are other options. – Philip Hanson Apr 11 '11 at 19:02