Wednesday, November 28, 2007

Have a child trigger a method in its parent

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/have_a_child_trigger_a_method_in_its_parent.htm]

Often you'll want to have a child object trigger some method in its parent. For example, you'll click a user control, but want that to change something in the parent control.  .Net 2.0 makes it very easy to do this. In .Net 1.1 (at least to my knowledge), this required a bunch of steps. Now, you can just add two lines in the object (declare a delegate, and then create an instance of that), and then use just one line in that object's consumer to specify the method to-be-called. In this case, we create an object "MyObject", with an event to be

namespace AddEvent
{
  public class Program
  {
    static void Main(string[] args)
    {
      MyOject o = new MyOject();
      o.GotClickedHandler += ParentGotClickedHandler;
      o.DoStuff();  //Trigger the object for some reason (this could come from a UI event like clicking it)
    }

    public static bool ParentGotClickedHandler(int i)
    {
      //I'm in the parent, but was triggered from the child object.
      i = i * 2;
      Console.WriteLine(i);
      return true;
    }

  }

  public class MyOject
  {

    public delegate bool GotClickedDelegate(int i);
    public GotClickedDelegate GotClickedHandler;


    public void DoStuff()
    {
      //trigger event:
      //trigger an event, passing that data
      int i = DateTime.Now.Second;

      if (this.GotClickedHandler != null)
      {
        GotClickedHandler(i);
      }
    }
  }
}

No comments:

Post a Comment