Raising external events of an object in C #

If actions is a Panel, can I raise this parent's Click event? I have this code at the moment, but the Click event is not a method, so this code is not valid.
Does anyone know how I can achieve this?

 actions.Click += delegate(object Sender, EventArgs e) { ((Panel)Sender).Parent.Click(); } 
+7
c # events raise
source share
5 answers

It is not possible to raise a C # event directly from another class (even if it is public ). You could provide a method (with a sufficient access modifier) ​​that raises event on your behalf and calls this method in another class .

By the way, this is possible with reflection, but I think it's a dirty hack.

+9
source share

Most types in the CLR that raises events have a protected [EventName] method that takes care of creating the event. You can call this protected method from the outside using Reflection:

  Control parent = ((Control)sender).Parent; Type parentType = parent.GetType(); MethodInfo onClickMethod = parentType.GetMethod("OnClick", BindingFlags.Instance | BindingFlags.NonPublic); onClickMethod.Invoke(parent, new object[] { e }); 
+6
source share

I implemented this using reflection and extension methods, so that I could just raise (in this case) the clickLabel event with a click, just by calling:

 var link = new LinkLabel()' link.Text = "Some link"; link.click(); 

The click () method is a C # extension method:

  public static void click(this LinkLabel linkLabel) { var e = new LinkLabelLinkClickedEventArgs((LinkLabel.Link)(linkLabel.prop("FocusLink"))); linkLabel.invoke("OnLinkClicked", e); } 

which uses other extension methods for:

  • get private property from LinkLabel (you must create a LinkLabelLinkClickedEventArgs object)
  • call the OnLinkClicked method (which will fire the event
+2
source share

Depending on which infrastructure you are using, you do not need to manually trigger the click event for the parent, WPF and ASP.NET , for example, bubble events in the element tree.

If this is not an option, you can do as Mehrdad suggests.

+1
source share

The only reason I can think of why you want to raise the Click event is because you are simulating user input. Are you working on an automated test driver or something like that? If so, there may be more effective solutions than using code with helper methods for testing purposes only. This appears first in google, I have no idea if this is good.

If you are trying to do this as a kind of flow control in your application, I would take a step back to see if it’s right to do it at all - it smells bad.

+1
source share

All Articles