Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tri-State Checkboxes in WinForms TreeView

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?

like image 202
Philip Hanson Avatar asked Apr 11 '11 18:04

Philip Hanson


2 Answers

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!

like image 157
Homam Avatar answered Oct 19 '22 19:10

Homam


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.

like image 11
PaulA Avatar answered Oct 19 '22 19:10

PaulA