Luke
Luke

Reputation: 544

Custom Component On Click Event

I've built a custom component that basically has a picture box and label in it. In the parent form, I want to be able to detect when its been clicked on. The standard .click event doesn't seem to be working, but I've never used events before so am unsure if I'm using them correctly. Heres the code I'm using (in the parent) to try and make it recognise the click:

Item aItem = new Item();
aItem.Icon = ItemImage;
aItem.Title = Title; 
aItem.Click += new EventHandler(ItemClicked);
aItem.Filename = File;

and heres the method its calling:

public void ItemClicked(Object sender, EventArgs e)
{
    MessageBox.Show("Item Clicked!");
}

This code never fires. Do I need to put anything into the component or am I just doing this wrong?

Cheers

Upvotes: 2

Views: 6085

Answers (2)

Luke
Luke

Reputation: 544

Right I finally worked it out. Tejs response just confused me more so here's what I did.

In my UserControl I had the following event:

public event EventHandler Clicked;

Then I had an event for when the image was clicked (still in the UserControl) and I just called the Clicked event:

private void imgItem_Click(object sender, EventArgs e)
{
    Clicked(this, e);
}

Then in my parent form, when I created the object, I had the following:

Item aItem = new Item();
aItem.Clicked += new EventHandler(ItemClicked);

void ItemClicked(object sender, EventArgs e)
{
    MessageBox.Show("Clicked!");
}

Upvotes: 3

Tejs
Tejs

Reputation: 41236

You would do this by exposing an event':

Your custom component:

// A custom delegate like MyItemClickedHandler, or you could make a Func<> or Action<>
public event MyItemClickedHandler ItemClickedEvent;

public void ItemClicked(object sender, EventArgs e)
{
    if(ItemClickedEvent != null)
      ItemClickedEvent(); // Your delegate could pass parameters if needed
}

Then your parent form simply observes the event:

myCustomControl.ItemClickedEvent += new MyItemClickedHandler(SomeMethod);

Then, whenever the event is raised on your custom control, the parent is notified because it subscribed the event.

Upvotes: 2

Related Questions