Writing commands
Commands provide a simple way to expose logic in the ArcGIS Map Web Part that should be initiated by the user. If it makes sense to have the functionality you are implementing initiated by having a user click a button on the ribbon, you should encapsulate this functionality in a command.
The Map Web Part exposes commands that implement the ICommand interface. This interface provides a few simple members. In the context of the Map Web Part, these members are used as follows:
- Execute—Called when the button on the ribbon corresponding to the command is clicked.
- CanExecute—Called frequently by the Map Web Part to check whether the command is in a state where it can be executed. When this method returns true, the corresponding button on the ribbon is enabled. When the method returns false, the button is unavailable.
- CanExecuteChanged—Event that can be raised when the executability of the command changes. When this event is raised, the Map Web Part invokes the CanExecute method, allowing the extension to update the state of the command's button on the ribbon.
In addition to implementing these members, you must also add two attributes to the class that implements ICommand. The first is System.ComponentModel.Composition.ExportAttribute, which is included in the System.ComponentModel.Composition assembly provided as part of Microsoft's Managed Extensibility Framework (MEF). This attribute informs the Map Web Part that the command should be made available for adding to the ribbon. When you include it on a command you implement, it will always take the following form:
[Export(typeof(ICommand))]
public class MyCommand : ICommand
The other attribute to add is ESRI.ArcGIS.Client.Extensibility.DisplayNameAttribute. This determines the name of the command as it appears to a designer when adding it to the Map Web Part. This attribute should be specified as follows:
[Export(typeof(ICommand))]
[DisplayName("<Name to display>")]
public class MyCommand : ICommand
An example of a simple command is shown below. The command displays a message box and is enabled when the map is not null. In this case, the CanExecuteChanged event is not used.
[Export(typeof(ICommand))]
[DisplayName("Simple Command")]
public class SimpleCommand : ICommand
{
public void Execute(object parameter)
{
// Show a message box when the command's ribbon button is clicked
MessageBox.Show("Simple command executed");
}
public bool CanExecute(object parameter)
{
// Show as executable (i.e. enable the button on the ribbon) unless the map is null
return MapApplication.Current.Map != null;
}
public event EventHandler CanExecuteChanged;
}