Handling the parent's events
I am trying to make a UserControl or Component which can be dragged from the Toolbox onto a container control such as a Form or a Panel. Its purpose is to change the behaviour of that container. In particular, I would like to add functions to the container's painting and mouse actions. I DO NOT want to have to write code for the container itself -- that's the whole point of the Toolbox object.
I can do this by getting a reference to the object's Parent (or Host in the case of a Component) and handling its events, as this example illustrates:
vb Code:
Public Class DeformablePolygon
Inherits Windows.Forms.UserControl
Private WithEvents _Parent As Windows.Forms.Control
Public Property VertexCollection As System.Drawing.PointF()
Protected Overrides Sub OnParentChanged(e As System.EventArgs)
_Parent = Me.Parent
MyBase.OnParentChanged(e)
End Sub
Private Sub _Parent_Paint(sender As Object, e As System.Windows.Forms.PaintEventArgs) Handles _Parent.Paint
If _VertexCollection IsNot Nothing Then
e.Graphics.DrawPolygon(System.Drawing.Pens.Black, _VertexCollection)
End If
End Sub
'+ mouse events etc.
End Class
However, I have heard that handling the events of a parent control conflicts with OOP principles. So I would like to know, does that objection apply in a case like my example? If so, what are the drawbacks? And what alternative techniques are available?
BB
Re: Handling the parent's events
What is the objection, in this case? The control has to have a parent, and that parent has to be of the right type. It does tie this object to the existence of an external object, but this object can't exist outside of the proper context, so that doesn't seem like a valid objection, in this case.
Re: Handling the parent's events
Thanks for your advice. That's the way I see it too, although I don't know what situation the "prohibition" applies to. So I'll carry on being cheeky to my _parents;). I'm still open to other comments, so I won't mark this resolved yet. BB