如何覆盖Control.Invalidate()方法?

时间:2012-09-17 11:54:49

标签: c# .net winforms drawing controls

我使用OwnerDrawAll属性作为我的控件:

this.customTreeView.DrawMode =System.Windows.Forms.TreeViewDrawMode.OwnerDrawAll;
this.customTreeView.DrawNode += 
    new System.Windows.Forms.DrawTreeNodeEventHandler(customTreeView_DrawNode);

private void customTreeView_DrawNode(object sender, DrawTreeNodeEventArgs e) {
   if(!myComboBoxChanged) {              // Draw the whole control(tree and info)
        drawNode(e);
        drawInfo(e);
   } else {                              // Draw only info
        drawInfo(e);
   }
}

然后我使用文本更改事件:

private void cBox_TextChanged(object sender, EventArgs e)
        {
            text = cBox.Text;                 // I need this in drawInfo()
            myComboBoxChanged = true;
            this.customTreeView.Invalidate();  // It doesn't do what I want
            myComboBoxChanged = false;
    }

这里重新绘制整个树的Invalidate()方法,如何修复此问题,以便仅调用drawInfo()

1 个答案:

答案 0 :(得分:0)

更好的方法是创建自己的TreeView类并封装所有方法和属性,以便:

public class MyTreeView : TreeView
{
    public bool TextBoxChanged { get; set; }
    public MyTreeView()
    {
        DrawMode = TreeViewDrawMode.OwnerDrawAll;
        DrawNode += new System.Windows.Forms.DrawTreeNodeEventHandler(customTreeView_DrawNode);


    }
    protected override void OnInvalidated(InvalidateEventArgs e)
    {
        //comment  the below line to create your own Invalidate
        //base.OnInvalidated(e);
    }

    private void customTreeView_DrawNode(object sender, DrawTreeNodeEventArgs e)
    {
        if (!TextBoxChanged)
        {              // Draw the whole control(tree and info)
            drawNode(e);
            drawInfo(e);
        }
        else
        {                              // Draw only info
            drawInfo(e);
        }
    }


    private void drawNode(DrawTreeNodeEventArgs e)
    {
        //...........
    }

    private void drawInfo(DrawTreeNodeEventArgs e)
    {
        //...........
    }
}