如何绘制单个treenode复选框状态以进行不确定

时间:2016-11-20 09:38:12

标签: c# winforms treeview

treenode有3种状态,带有复选框,已选中,未选中且不确定(方形)。

我的问题是如何绘制不确定状态?

我有以下代码,它将3个复选框添加到树视图图像列表中:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
  public partial class Form1 : Form
  {
    public Form1()
    {
        InitializeComponent();

        treeView1.StateImageList = new System.Windows.Forms.ImageList();

        // populate the image list, using images from the System.Windows.Forms.CheckBoxRenderer class
        for (int i = 0; i < 3; i++)
        {
            // Create a bitmap which holds the relevent check box style
            // see http://msdn.microsoft.com/en-us/library/ms404307.aspx and http://msdn.microsoft.com/en-us/library/system.windows.forms.checkboxrenderer.aspx

            System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(16, 16);
            System.Drawing.Graphics chkGraphics = System.Drawing.Graphics.FromImage(bmp);
            switch (i)
            {
                // 0,1 - offset the checkbox slightly so it positions in the correct place
                case 0:
                    System.Windows.Forms.CheckBoxRenderer.DrawCheckBox(chkGraphics, new System.Drawing.Point(0, 1), System.Windows.Forms.VisualStyles.CheckBoxState.UncheckedNormal);
                    break;
                case 1:
                    System.Windows.Forms.CheckBoxRenderer.DrawCheckBox(chkGraphics, new System.Drawing.Point(0, 1), System.Windows.Forms.VisualStyles.CheckBoxState.CheckedNormal);
                    break;
                case 2:
                    System.Windows.Forms.CheckBoxRenderer.DrawCheckBox(chkGraphics, new System.Drawing.Point(0, 1), System.Windows.Forms.VisualStyles.CheckBoxState.MixedNormal);
                    break;
            }

            treeView1.StateImageList.Images.Add(bmp);
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        TreeNode n = new TreeNode("Root");
        n.SelectedImageIndex = 2;
        n.Nodes.Add("asd");
        treeView1.Nodes.Add(n);
    }
  }
}

但是当我设置treenode的SelectedImageIndex = 2

什么都没发生..

1 个答案:

答案 0 :(得分:0)

您已将3张图片添加到StateImageList,但(int)CheckBoxState.MixedNormal评估为9

12 CheckBoxStates因此您需要创建更多图片或折叠索引以保持在您的范围内:

treeView1.SelectedImageIndex = ((int)CheckBoxState.MixedNormal) / 4;

(除了disabled之外,您没有考虑pressedhotnormal州。)

您确实将treeView1.StateImageList设置为您的StateImageList treeView1.ImageList设置为其他Imagelist当然?