Using VS2010 on .NET v4 I have the following problems.
I have created two custom Controls, Cell and Board and I want to use the Cell control to capture a number of events and to display some data. The most important event I need to capture is the Click event.
When the custom control has no child control items this is not a problem.
At the level wher Cell is used I can bind an event handler to the Click event with no problem.
public partial class Cell : UserControl
{
....
}
public partial class Board : UserControl
{
private void InitializeComponent()
{
...
this.Cell99.Click += new System.EventHandler(this.Cell_Click);
...
}
}
The Cell control is rather small (about 50×50 pixels in size) and one of the things I want it to display is an integer value as big as possible (about 50 x 50 pixes in size 😉 No problem in doing that, I want to use a Label control for that.
As soon as I add another (e.g. Label) control to Cell it no longer can see some events because the child event is getting ‘first rights’ on it. For the pixels that are covered by the Label control it will capture the Click event that I want to handle with the Cell control and not with the Label contol.
If it was only one control that I want to use in Cell the solution would be to link the event from the Label control to the Cell control. But I have at least 10 different (Label) controls that need to go in Cell to display all the information I have. Forwarding all the events for all the controls to its parent looks like a bit of a hassle to me. (Except from being prone to errors and other bugs.)
What is the propper way of disabling event capturing for child controls in a user control?
As said I have thought of forwarding events from child to parent but rejected that for now.
Then I have thought of not using controls to display the data but generate a bitmap with the information in it and use that as a background. I’m… not looking forward to that!
And finaly I came with an idea of putting one extra control, on top of all the others, and forward the events it’s captures to the parent. That might be the simplest way to continue.
Somehow I thing there must be a better way to approach this problem but how?
Any advise is welcome.
Implement a label class which inherits from Windows.Forms.Label. In this derived label/component class add a method or mechanism to forward any click event received by the label to the parent Cell control. Any labels which are added as child controls of a Cell would be of this custom label class and would all forward their Click events to the parent without having to manually do so for each label instance.