Writing map behaviors

Map behaviors provide a simple way to expose functionality in the Map Web Part that should always be enabled. If you are developing functionality to add a capability or modification to the Map Web Part that should always be present, this should be encapsulated as a map behavior. Map behaviors can be used, for instance, to keep the map at a certain extent or expose a method externally to JavaScript or Silverlight messaging.

Behaviors that are developed for use with the Map Web Part must inherit from System.Windows.Interactivity.Behavior<ESRI.ArcGIS.Client.Map>. The Behavior<T> base class provides a few simple members. In the context of the Map Web Part, these members are used as follows:

To make a behavior available for designers to add to the Map Web Part, you must add two attributes to your behavior class. The first is System.ComponentModel.Composition.ExportAttribute, which is included in the System.ComponentModel.Composition assembly provided as part of the Microsoft Managed Extensibility Framework (MEF). This attribute informs the Map Web Part that the behavior should be made available. When you include it on a behavior you implement, it will always take the following form: Export Attribute.

[Export(typeof(Behavior<Map>))]
public class MyBehavior : Behavior<Map>

The other attribute to add is ESRI.ArcGIS.Client.Extensibility.DisplayNameAttribute. This determines the name of the behavior as it appears to a designer when adding it to the Map Web Part. This attribute should be specified as follows:

[Export(typeof(Behavior<Map>))]
[DisplayName("<Name to display>")]
public class MyBehavior : Behavior<Map>

An example of a simple behavior is shown in the following code. The behavior adds a handler to the map's ExtentChanged event when the behavior is attached to the map and removes it when the behavior is detached. The behavior shows a message box with the current extent when the extent changes.

[Export(typeof(Behavior<Map>))]
[DisplayName("Simple Behavior")]
public class MyBehavior : Behavior<Map>
{
     protected override void OnAttached()
     {
          base.OnAttached();
 
          // Add a handler to the map's ExtentChanged event.
          this.AssociatedObject.ExtentChanged += OnExtentChanged;
     }
 
     private void OnExtentChanged(sender s, ExtentEventArgs args)
     {
          // Show a message box with the new extent.
          MessageBox.Show(this.AssociatedObject.Extent.ToString());
     }
 
     protected override void OnDetaching()
     {
          // Remove the handler from the map's ExtentChanged event.
          this.AssociatedObject.ExtentChanged -= OnExtentChanged;
     }
}

11/30/2012