Sometimes it is possible to use Handles with nested objects (like ... Handles WithEventsVariable.Property.Event). But certain specific conditions must be met to achieve this.
- WithEventsVariable must be field declared WithEvents.
- Type of WithEventsVariable must be Class (not structure, not interface)
- The Property must be readonly property of WithEventsVariable class
- The Property must be docorated with <DesignerSerializationVisibility(DesignerSerializationVisibity.Content)> attribute
- The Event must be event of Property type
- Type of property must be either Interface or Class (no structure)
Intellisense support for thsi is limited. In case Handles does not work, you can still use AddHandler.
Example
This example needs form with docked FlowLayoutPanel FlowLayoutPanel1.
Imports System.ComponentModel
Public Class Form1
PublicSubNew()
InitializeComponent()
FlowLayoutPanel1.Controls.Add(cWithReadOnlyButton.Button)
EndSub
Private WithEvents cWithReadOnlyButton As New ClassWithReadOnlyButton
Private Sub cWithReadOnlyButton_Button_Click(ByVal sender As Button, ByVal e As EventArgs) _
Handles cWithReadOnlyButton.Button.Click
MsgBox( _
"You've clicked: " & sender.Text, _
MsgBoxStyle.Information, _
"2-dotted event on class")
End Sub
End Class
Friend Class ClassWithReadOnlyButton
Private _Button As New Button _
With {.Text = "Click me!", _
.AutoSize = True, _
.AutoSizeMode = AutoSizeMode.GrowAndShrink}
<DesignerSerializationVisibility(DesignerSerializationVisibility.Content)> _
Public ReadOnly Property Button() As Button
Get
Return _Button
End Get
End Property
End Class