日期:2014-05-18  浏览次数:20927 次

关于用户控件继承容器的功能
我想为自定义的用户控件加上容器功能。。指的是当在窗体画上此用户控件时。。。再在此用户控件内绘画其它控件。。。当移动此用户控件时。在内的其它控件都随之移动。是不是要实现某个接口。。。???我知道有个可以直接继承的容器类。。。但是C#不支持多继承。。若继承了这个容器类的话。就不能提供设计界面了(就像一个类不继承窗体类就没法直接编辑界面一样)。。。。如何才能实现一个功能。。既能实现容器功能。又可以为这个类提供设计界面。。()

------解决方案--------------------
给类定义加上DesignerAttribute:[Designer("System.Windows.Forms.Design.ParentControlDesigner, System.Design", typeof(IDesigner))]
------解决方案--------------------
可以自定义容器控件啊
VB.NET code

'自定义控件代码
Public Class TestControl

    Dim MouseDownPt As Point

    Public Sub New()

        ' 此调用是 Windows 窗体设计器所必需的。
        InitializeComponent()

        ' 在 InitializeComponent() 调用之后添加任何初始化。
        Me.SetStyle(ControlStyles.ContainerControl, True)
    End Sub

    Private Sub TestControl_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseDown
        MouseDownPt = e.Location
    End Sub

    Private Sub TestControl_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseMove
        If e.Button = Windows.Forms.MouseButtons.Left Then
            Dim dx As Integer = e.X - MouseDownPt.X
            Dim dy As Integer = e.Y - MouseDownPt.Y
            Me.Location = New Point(Me.Location.X + dx, Me.Location.Y + dy)
        End If
    End Sub

End Class

'测试窗体代码(窗体添加一个TestControl1控件)
Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim NewBtn As New Button
        Dim NewCheckBox As New CheckBox
        Me.TestControl1.Controls.Add(NewBtn)
        Me.TestControl1.Controls.Add(NewCheckBox)
        NewBtn.Text = "Button1"
        NewBtn.Location = New Point(10, 10)
        NewCheckBox.Text = "CheckBox1"
        NewCheckBox.Location = New Point(10, 50)
    End Sub

    
End Class