How do I handle the Click event on a control when a child control is clicked?
I have UserControl
one that has other controls:
I need to enable click on any element that I click on the custom control, so I can set the border style of the UserControl.
This works if I don't have any control, but if I have a panel and I try to click on the panel, my ClickControl event does not fire.
This is my code:
public partial class TestControl : UserControl
{
public TestControl()
{
InitializeComponent();
this.Click += Item_Click;
IsSelected = false;
}
public bool IsSelected { get; set; }
void Item_Click(object sender, EventArgs e)
{
if (!IsSelected)
{
IsSelected = true;
this.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
}
else
{
IsSelected = false;
this.BorderStyle = System.Windows.Forms.BorderStyle.None;
}
}
}
Any hint on how to fire my ClickControl event even if I click on other elements?
+3
source to share
1 answer
It's actually very easy to achieve this goal, you can iterate over all the controls contained in your UserControl and register Item_Click
in your EventHandler that will call it when the Click event fires:
public partial class TestControl : UserControl {
public TestControl( ) {
//...
for ( int i = 0; i < Controls.Count; i++ ) {
Controls[ i ].Click += Item_Click;
}
}
//...
}
+1
source to share