让自定义控件成为容器

我希望自定义的控件打开后,可以将工具栏上的控件拖到该自定义控件上。观察了Pannel控件,似乎简单得很。

继承自ScrollableControl,而ScrollableControl继承自Control。两个类都没有重写绘制,只是增加一些属性和重写某些属性值。而Control有一个Controls的集合属性。似乎已做了大部分的事。


我尝试直接往Control.Controls添加一个Button

代码
public class TrackPannel:Control
{
//...
    private void drawTrack(Graphics gc,Rectangle rect)
        {
            
int iBottonY = rect.Y + rect.Height;
            
int iCur = 0;
            
//int iIndex = 0;
            while (iCur < rect.Width)
            {
                
//iIndex++;
                iCur = iCur + this.TackSpacing;
                gc.DrawLine(Pens.Black, iCur, 
2, iCur, iBottonY);
            }
            Button btn 
= new Button();
            btn.Click 
+= new EventHandler(btn_Click);
            
this.Controls.Add(btn);
        } 
//
 

Button能正常显示,并接收到点击事件。证明我的想法是对的。再细看ScrollableControl,原来需要两步

1.设置ControlStyles.ContainerControl

2.设置Designer

以下是修改后的代码。

代码
[Designer("System.Windows.Forms.Design.ParentControlDesigner,System.Design",
  
typeof(System.ComponentModel.Design.IDesigner))]
public class TrackPannel:Control

        
/// <summary>
        
/// 构造函数
        
/// </summary>
        public TrackPannel()
        {            
            
base.SetStyle(ControlStyles.UserPaint, true);
            
base.SetStyle(ControlStyles.ContainerControl, true);
        }
//...


base.SetStyle(ControlStyles.UserPaint, true);”是告诉程序用控件自己重写的OnPaint。重写了还不行,还要非得设置这个!一时半会,真让人摸不着边。

posted @ 2010-03-04 17:02  生命体验之kevin-Y  阅读(1066)  评论(0编辑  收藏  举报