Практические советы: Создание настраиваемых компонентов

Создание настраиваемых инструментов и поведений

Расширяемый API позволит вам делать собственные инструменты и поведения настраиваемыми. Если инструмент или поведение настраиваемы, вы можете изменять их компоненты при создании их представления. Чтобы работать с настройкой инструмента или поведения, вам необходим интерфейс ESRI.ArcGIS.Client.Extensibility.ISupportsConfiguration. Этот интерфейс требует включения следующих методов:

Для примера настраиваемого инструмента представим, что вы создали простой элемент управления UserControl, содержащий код и текстовое окно. Текст Extensible Application Markup Language (XAML) для такого элемента управления может выглядеть примерно так:

<UserControl x:Class="MyExtension.ConfigurationDialog"
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
     mc:Ignorable="d"
     d:DesignHeight="300" d:DesignWidth="400">
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <StackPanel Margin="10" Background="Transparent">
            <TextBlock Text="Configuration Input:" Margin="0,0,0,5" />
            <TextBox Name="InputTextBox" Width="200" />
        </StackPanel>
    </Grid>
</UserControl>

Элемент может использоваться в простом настраиваемом инструменте следующим образом:

[Export(typeof(ICommand))]
[DisplayName("Configurable Command")]
[Category("My Tools")]
[Description("Example of a configurable command")]
[DefaultIcon(Path to icon, ex: "/Viewer.Addins;component/Images/Identify.png")]
public class ConfigurableCommand: ICommand, ISupportsConfiguration
    {
        private ConfigurationDialog configDialog = new ConfigurationDialog();

        #region ISupportsConfiguration Members

        public void Configure()
        {
            // When the dialog box opens, it shows the information saved from the last 
												//time the command was configured.
            MapApplication.Current.ShowWindow("Configuration", configDialog);
        }

        public void LoadConfiguration(string configData)
        {
            // If the saved configuration is not null, apply it to the configuration dialog box.
            configDialog.InputTextBox.Text = configData ?? "";
        }

        public string SaveConfiguration()
        {
            // Save the information from the dialog box, and 
            return configDialog.InputTextBox.Text;
     
        }

        #endregion

        #region ICommand Members

        public bool CanExecute(object parameter)
        {
            // Return true so that the command can always be executed.
            return true;
        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            // Show the configuration data. 
            MapApplication.Current.ShowWindow("Configuration", new TextBlock()
            {
                Text = configDialog.InputTextBox.Text,
                TextWrapping = TextWrapping.Wrap,
                Margin = new Thickness(30),
                MaxWidth = 480
            });
        }

        #endregion
    }

Нажатие кнопки Настроить (Configure) в диалоговом окне инструмента приведет к вызову метода Настроить (Configure) для соответствующего инструмента. В случае, показанном выше, будет отображено следующее диалоговое окно:

Диалоговое окно настройки

Если вьюер открыт или сохранен, текст в поле сохраняется как строка. Если вьюер загружен, строка передается в метод LoadConfiguration и используется для инициализации строковой переменной. При запуске команды – с помощью нажатия кнопки команды – будет отображено сообщение с сохраненной строкой настройки:

Диалоговое окно с сохраненной строкой настройки

1/23/2014