How to: Register to be Notified on an Event

Events are fired when changes are made to a model. You can subscribe to an event so that you can receive notification when the event is fired. To subscribe to an event, use EventManagerDirectory.

The event arguments parameter contains information that you can use in your custom code, such as the element added or deleted or with a property being changed. For example, for an ElementPropertyChanged event, the event arguments parameter provides the old value and the new value of the property.

To write custom code that runs when an event is fired

  1. Write an event handler method with the custom code that you want run when a specific event occurs.

  2. Create a delegate for the event handler.

  3. Assign the method to the delegate.

  4. Use the Add method of one of the EventManagerDirectory properties to register to be notified when that event is fired.

    When you are finished listening for events, use the Remove method to disable notification.

Example

The following example registers an event handler to be notified after an element is added to the model.

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.Modeling;

namespace Fabrikam
{
  public class Class1
  {
     private EventHandler<ElementAddedEventArgs> elementAddedEventHandler;
      public void DoSomething()
      {
         this.elementAddedEventHandler = this.HandleElementAdded;
         Store s = new Store();
         s.EventManagerDirectory.ElementAdded.Add(this.elementAddedEventHandler);

         // Start transaction, add elements, commit the transaction 

         s.EventManagerDirectory.ElementAdded.Remove(this.elementAddedEventHandler);

      }

      public void HandleElementAdded(object sender, EventArgs e)
      {
        // your custom code goes here
      }
      
   }
}

By using an instance of the store, you can subscribe to an event before you make any changes to the store.

The Add method has three overrides. You can pass in a delegate, as in the example, and you will be notified whenever any element is added.

You can also pass in a delegate and a domain class, which notifies you only when an element of that type is added. You can use another overload to pass in a delegate and a domain model so that you are notified whenever any kind of element is added to that type of model.

See Also

Concepts

Comparing Events and Rules