使用 DrawMode: OwnerDrawText

问题描述 投票:0回答:1

我正在使用具有 DrawMode 的树视图(Windows 窗体):TreeViewDrawMode.OwnerDrawText。但我在渲染内容时遇到问题。在树视图完全初始化之前,树视图节点绘制在树视图的第一行,如下所示:

树视图完全初始化后,一切都绘制得很好:

但我不想看到您在第一个屏幕截图中看到的渲染预初始化。 有时,当树视图加载速度非常快时,这种预初始化是不可见的。 可能和OwnerDrawText模式渲染速度比较慢有关?

我用于DrawTreeNodeEventsArgs事件的代码如下:

private void myTreeView_DrawNode(
object sender, DrawTreeNodeEventArgs e)
{
    //Draw the background and node text for a selected node.
    if ((e.State & TreeNodeStates.Selected) != 0)
    {
        e.Graphics.FillRectangle(Brushes.AliceBlue, NodeBounds(e.Node));
    }
    else
    {
        if (e.Node.Name != null)
        {
            int color;
            bool isValidInt = int.TryParse(e.Node.Name.ToString(), out color);

            if (isValidInt)
            {
                Brush colorBrush = new SolidBrush(Color.FromArgb(color));
                //e.Graphics.FillRectangle(colorBrush, new Rectangle(e.Bounds.Right + 2, e.Bounds.Top, 10, 10));

                e.Graphics.FillRectangle(colorBrush, new Rectangle(e.Bounds.Left + 2, e.Bounds.Top + 2, 10, 10));

                e.Graphics.DrawString(e.Node.Text.ToString(), tagFont,
                Brushes.Black, e.Bounds.Left + 12, e.Bounds.Top);

            }
            else
            {
                e.DrawDefault = true;
            }
        }
    }

    if ((e.State & TreeNodeStates.Focused) != 0)
    {
        //e.Graphics.FillRectangle(Brushes.AliceBlue, NodeBounds(e.Node));

        //using (Pen focusPen = new Pen(Color.Black))
        //{
        //    focusPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;
        //    Rectangle focusBounds = NodeBounds(e.Node);
        //    focusBounds.Size = new Size(focusBounds.Width - 1,
        //    focusBounds.Height - 1);
        //    e.Graphics.DrawRectangle(focusPen, focusBounds);
        //}
    }
}

有人知道如何防止第一个屏幕截图中出现的预初始化渲染效果吗?好的,提前谢谢。

c# winforms treeview rendering
1个回答
0
投票

你可以尝试这样的事情:

private bool isExpandingOrCollapsing = false;

    protected override void OnBeforeExpand(TreeViewCancelEventArgs e)
    {
        isExpandingOrCollapsing = true;

        this.BeginUpdate();
        base.OnBeforeExpand(e);
    }

    protected override void OnAfterExpand(TreeViewEventArgs e)
    {
        isExpandingOrCollapsing = false;

        base.OnAfterExpand(e);
        this.EndUpdate();
    }

    protected override void OnAfterCollapse(TreeViewEventArgs e)
    {
        base.OnAfterCollapse(e);
        this.EndUpdate();
    }

然后在绘图子中,检查 isExpandingOrCollapsing 值:

    protected override void OnDrawNode(DrawTreeNodeEventArgs e)
    {
        //do not draw if not visible
        if (e.Node.IsVisible == false) return;

        // do not draw if extanding or collapsing
        if (isExpandingOrCollapsing) return;
 ...}
© www.soinside.com 2019 - 2024. All rights reserved.