在树视图中更改子节点的背景颜色

时间:2013-10-04 10:21:01

标签: c# user-interface treeview components

根据TreeView Remove CheckBox by some Nodes

执行此操作后,我tree-view的{​​{1}} check-box没有parent node check-box。 但是我遇到了一个问题,我无法改变特定子节点的颜色。

即。如果我试着改变

treeview1.Nodes[0].Nodes[2].BackColor=Color.Gray;

仍然具有相同的旧颜色。 谁可以帮我这个事。 感谢。

被修改

private const int TVIF_STATE = 0x8;
    private const int TVIS_STATEIMAGEMASK = 0xF000;
    private const int TV_FIRST = 0x1100;
    private const int TVM_SETITEM = TV_FIRST + 63;

    [StructLayout(LayoutKind.Sequential, Pack = 8, CharSet = CharSet.Auto)]
    private struct TVITEM
    {
        public int mask;
        public IntPtr hItem;
        public int state;
        public int stateMask;
        [MarshalAs(UnmanagedType.LPTStr)]
        public string lpszText;
        public int cchTextMax;
        public int iImage;
        public int iSelectedImage;
        public int cChildren;
        public IntPtr lParam;
    }

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam,
                                             ref TVITEM lParam);

    /// <summary> 
    /// Hides the checkbox for the specified node on a TreeView control. 
    /// </summary> 
    private void HideCheckBox(TreeView tvw, TreeNode node)
    {
        TVITEM tvi = new TVITEM();
        tvi.hItem = node.Handle;
        tvi.mask = TVIF_STATE;
        tvi.stateMask = TVIS_STATEIMAGEMASK;
        tvi.state = 0;
        SendMessage(tvw.Handle, TVM_SETITEM, IntPtr.Zero, ref tvi);
    }

    /// <summary>
    /// Handles the DrawNode event of the treeView1 control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Windows.Forms.DrawTreeNodeEventArgs"/> instance containing the event data.</param>
    /// <remarks></remarks>
    private void treeView1_DrawNode(object sender, DrawTreeNodeEventArgs e)
    {
        if (e.Node.Level == 0)
            HideCheckBox(e.Node.TreeView, e.Node);
        e.DrawDefault = true;           
    }




    private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
    {          

        treeView1.Nodes[0].Nodes[1].BackColor = Color.Red;
    }

1 个答案:

答案 0 :(得分:3)

我已经按照您的方式尝试了(特别是DrawNode事件处理程序)并且我非常确定您设置了TreeView.DrawMode = TreeViewDrawMode.OwnerDrawText;。这不会绘制Background(仅Text),这样就不会更新BackColor的原因。您必须将其设置为TreeViewDrawMode.OwnerDrawAll

我会使用另一种方法Hide所有Child node checkboxes而不使用DrawNode事件处理程序。我会像BeforeExpand这样添加代码:

 //BeforeExpand event handler for your TreeView
 private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e){
   foreach (TreeNode node in e.Node.Nodes) 
       HideCheckBox(e.Node.TreeView, e.Node);
 }

您还可以使用level>0循环浏览所有节点,以隐藏一次复选框。然后,每当您向TreeView添加更多节点时,如果它不是level 0 node,则在添加后立即HideCheckBox

注意:当然,我上面提到的两种方法要求您将DrawMode设置为Normal以外的任何其他方式