首页 > 解决方案 > 未显示根线时,TreeView 将 +- 号添加到根节点

问题描述

我有一个包含多个根节点的树视图。这些根节点不相关,因此通过设置ShowRootLines为删除根线false。每个根节点包含多个子节点。

我知道当ShowRootLines是时false,加号/减号将为根节点禁用,但仍会在必要时在子节点上显示。

但是我需要为根节点启用加号/减号,而ShowRootLines = false. 这可能吗?如何将 +- 符号添加到根节点?

谢谢你。

标签: c#winformstreeview

解决方案


这是一种可能的解决方案,它监听WM_PAINT消息,然后删除这些点。

private class MyTreeView : TreeView {

    public static void AddNodes(TreeView tv) {
        var root = tv; //.Add("");
        var a = root.Nodes.Add("A");
        a.Nodes.Add("aa1");
        var aa2 = a.Nodes.Add("aa2");
        aa2.Nodes.Add("aaa1");
        aa2.Nodes.Add("aaa2");
        var b = root.Nodes.Add("B");
        b.Nodes.Add("bb");
        var c = root.Nodes.Add("C");
        c.Nodes.Add("cc");
        tv.ExpandAll();
    }

    public MyTreeView() {
        AddNodes(this);
    }

    private const int WM_PAINT = 0xf;

    protected override void WndProc(ref Message m) {
        base.WndProc(ref m);
        if (m.Msg == WM_PAINT) {
            EraseRootLines();
        }
    }

    private void EraseRootLines() {
        using (Graphics g = Graphics.FromHwnd(this.Handle)) {
            using (Bitmap bmp = new Bitmap(16, this.Height)) {
                this.DrawToBitmap(bmp, new Rectangle(0, 0, 16, this.Height));
                int w = 16 - 1;
                int h = this.Height - 1;
                int dotx = 0;
                int doty = 0;
                // find the first single pixel, which gives the x position of the vertical root line to erase
                Color dotc = Color.Empty; // dot color
                Color dotw = Color.Empty; // white color
                for (int j = 1; j < w; j++) {
                    for (int i = 1; i < h; i++) {
                        Color c = bmp.GetPixel(j, i);
                        Color c1 = bmp.GetPixel(j-1, i);
                        Color c2 = bmp.GetPixel(j+1, i);
                        Color c3 = bmp.GetPixel(j, i-1);
                        Color c4 = bmp.GetPixel(j, i+1);
                        if (c != c1 && c1 == c2 && c1 == c3 && c1 == c4) {
                            dotc = c;
                            dotw = c1;
                            dotx = j;
                            doty = i;
                            break;
                        }
                    }
                }

                // scan down the line looking for pixels with a 'white' color on either side
                // this could be optimized to fill by regions rather than individual dots
                for (int i = doty - 2; i < h; i++) {
                    Color c = bmp.GetPixel(dotx, i);
                    Color c3 = bmp.GetPixel(dotx - 1, i);
                    Color c4 = bmp.GetPixel(dotx + 1, i);
                    if (c == dotc && c3 == dotw && c4 == dotw) {
                        g.FillRectangle(Brushes.White, dotx - 2, i - 2, 1, 1);
                    }
                }
            }
        }
    }
}

推荐阅读