> For the complete documentation index, see [llms.txt](https://wfsys.gitbook.io/wt-practice/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://wfsys.gitbook.io/wt-practice/advanced/lesson_includes.md).

# Урок 27. Разделение формы на несколько файлов

## Включение документов

Платформа Workflow Technology поддерживает механизм разделения формы на несколько файлов. Для этого используется тэг [\<Includes>](https://wfsys.gitbook.io/workflow-forms-syntax/workflow_forms/includes), который описывается в основном файле и содержит ссылку на дополнительный xml-файл.

```xml
<Includes>
  <Include Path="IncludeDocument.xml" />
</Includes>
```

В момент открытия формы платформа парсит xml-файл и загружает включаемые документы, копируя их содержимое в экземпляр класса WorkflowForm, созданный для формы из основного файла. Сами файлы при этом никак не изменяются.

Механизм включения документов поддерживает любой уровень вложенности. Если в цепочке вложений файл будет упоминаться несколько раз, то он все равно будет загружен только один раз.

{% hint style="warning" %}
Подстановка текста из файлов строковых ресурсов (ru.wxlf и en.wxlf) будет производиться **после** загрузки включаемых файлов. Следовательно, используемые во включаемых файлах строки должны быть описаны либо в контексте основного файла, либо в общем контексте.
{% endhint %}

Разбиение формы на несколько файлов можно использовать в разных случаях. Например:

* создание файла стилей, чтобы не дублировать тэг `<Appearance>` во всех файлах форм;
* вынесение общих условий или команд. Например, можно вынести условия и команды, связанные с паттерном [onClose](https://wfsys.gitbook.io/wt-practice/main/lesson_4).

### Файл стилей

Создадим файл формы \_TemplateAppearance.xml, который будет выступать в качестве источника стилей и цветов для остальных форм. Добавим в него только описание тэга `<Appearance>`. Полный код файла будет иметь вид:

{% code title="\_TemplateAppearance.xml" %}

```xml
<?xml version="1.0"?>
<Form Name="NewForm" Title="FormTitle" Width="800" Height="600" StartPosition="CenterScreen" FontStyle="TitleFont" ForeColor="Black" StatusBar="True" MaximizeBox="False">
  <Appearance>
    <Colors>
      <Color Name="ThemeForeColor" Red="0" Green="0" Blue="0" Alpha="255" />
      <Color Name="ThemeBackgroundColor" Red="255" Green="255" Blue="255" Alpha="255" />
      <Color Name="ThemeFlatColor" Red="255" Green="0" Blue="0" Alpha="255" />
      <Color Name="ThemeSeparateBackgroundColor" Red="225" Green="225" Blue="225" Alpha="255" />

      <Color Name="HeadBackgroundColor" Red="221" Green="232" Blue="246" Alpha="255" />
      <Color Name="HeadForeColor" Red="70" Green="70" Blue="70" Alpha="255" />

      <Color Name="LabelForeColor" Red="100" Green="100" Blue="100" Alpha="255" />
      <Color Name="TableBackgroundColor" Red="200" Green="200" Blue="200" Alpha="255" />
      <Color Name="TableArchiveColor" Red="230" Green="230" Blue="230" Alpha="255" />

      <!-- Стили кнопок -->
      <Color Name="ButtonFlatBorderColor" Red="225" Green="225" Blue="225" Alpha="255" />
      <Color Name="ButtonFlatMouseDownBackColor" Red="201" Green="219" Blue="241" Alpha="255" />
      <Color Name="ButtonFlatMouseOverBackColor" Red="228" Green="237" Blue="248" Alpha="255" />
    </Colors>

    <FontStyles>
      <FontStyle Name="ThemeFontStyle" Font="Segoe UI" Size="9" />
      <FontStyle Name="HeadFontStyle" Font="Segoe UI" Size="15" />
      <FontStyle Name="LabelFontStyle" Font="Segoe UI" Size="9" Italic="True" />
      <FontStyle Name="ButtonFontStyle" Font="Segoe UI" Size="10" />
    </FontStyles>
  </Appearance>  
</Form>
```

{% endcode %}

{% hint style="info" %}
Значения атрибутов тэга \<Form> не будут играть никакой роли, так как файл будет выступать источником вложенных тэгов.
{% endhint %}

Перейдем в файл формы настроек пользователя (TemplateUserSettings.xml), в котором удалим тэг `<Appearance>` и вместо него добавим тэг `<Includes>`:

{% code title="TemplateUserSettings.xml" %}

```xml
<Includes>
  <Include Path="_TemplateAppearance.xml" />
</Includes>
```

{% endcode %}

В качестве значения атрибута `Path` тэга `<Include>` укажем имя нашего файла стилей.

Запустите приложение и проверьте отображение формы пользовательских настроек.

### Вынесение общих условий или команд

Создадим файл \_TemplateOnClose.xml, в который из файла TemplateUserSettings.xml перенесем:

* условия FormClosingCondition, EscapeKeyDownCondition, FormChangedEqualCondition и MandatoryFieldsAreFilledEqualCondition;
* команды FormCloseCommand, SaveOnCloseMessageBoxCommand и CloseOnCloseMessageBoxCommand;
* а также весь тэг `<Executions>`, так как все Execution связаны с паттерном onClose.

<details>

<summary>Полный код файла _TemplateOnClose</summary>

{% code title="\_TemplateOnClose.xml" %}

```xml
<?xml version="1.0"?>
<Form Name="NewForm" Title="FormTitle" Width="800" Height="600" StartPosition="CenterScreen" FontStyle="TitleFont" ForeColor="Black" StatusBar="True" MaximizeBox="False">

  <Conditions>
    <Condition Name="FormClosingCondition" Type="FormClosingCondition" Assembly="Conditions" />

    <Condition Name="EscapeKeyDownCondition" Type="KeyDownCondition" Assembly="Conditions">
      <Key Value="Escape" />
    </Condition>

    <Condition Name="FormChangedEqualCondition" Type="EqualCondition" Assembly="Conditions">
      <Items>
        <Item>
          <Form>
            <Property Name="FormChanged" />
          </Form>
        </Item>
        <Item>True</Item>
      </Items>
      <DataType Type="BooleanDataType" />
    </Condition>

    <Condition Name="MandatoryFieldsAreFilledEqualCondition" Type="EqualCondition" Assembly="Conditions">
      <Items>
        <Item>
          <Form>
            <Property Name="CheckingFired" />
          </Form>
        </Item>
        <Item>False</Item>
      </Items>
      <DataType Type="BooleanDataType" />
    </Condition>
  </Conditions>

  <Commands>
    <Command Name="FormCloseCommand" Type="FormCloseCommand" Assembly="Commands" />

    <Command Name="SaveOnCloseMessageBoxCommand" Type="MessageBoxCommand" Assembly="Commands">
      <Caption>
        <Text Id="SaveOnCloseMessageBox.Caption">Сохранение</Text>
      </Caption>
      <Text>
        <Text Id="SaveOnCloseMessageBox.Text">Форма содержит несохраненные изменения.\rСохранить их перед закрытием?</Text>
      </Text>
      <Icon Type="Question" />
      <Buttons Type="YesNoCancel" />
    </Command>

    <Command Name="CloseOnCloseMessageBoxCommand" Type="MessageBoxCommand" Assembly="Commands">
      <Caption>
        <Text Id="CloseOnCloseMessageBox.Caption">Закрытие</Text>
      </Caption>
      <Text>
        <Text Id="CloseOnCloseMessageBox.Text">При закрытии все несохраненные изменения будут утеряны.\rВы уверены, что хотите закрыть форму?</Text>
      </Text>
      <Icon Type="Question" />
      <Buttons Type="YesNo" />
    </Command>
  </Commands>

  <Executions>
    <Execution>
      <ConditionExpression>
        <Or>
          <And>
            <Or>
              <Condition Name="FormClosingCondition" />
              <Condition Name="EscapeKeyDownCondition" />
            </Or>
            <Not>
              <Condition Name="FormChangedEqualCondition" />
            </Not>
          </And>
          <Command Name="SaveOnCloseMessageBoxCommand" Parameter="No" />
          <Command Name="CloseOnCloseMessageBoxCommand" Parameter="Yes" />
        </Or>
      </ConditionExpression>
      <Commands>
        <Command Name="FormCloseCommand" />
      </Commands>
    </Execution>

    <Execution>
      <ConditionExpression>
        <And>
          <Or>
            <Condition Name="FormClosingCondition" />
            <Condition Name="EscapeKeyDownCondition" />
          </Or>
          <Condition Name="FormChangedEqualCondition" />
        </And>
      </ConditionExpression>
      <Commands>
        <If>
          <When>
            <Condition Name="MandatoryFieldsAreFilledEqualCondition" />
          </When>
          <Then>
            <Command Name="SaveOnCloseMessageBoxCommand" />
          </Then>
          <Else>
            <Command Name="CloseOnCloseMessageBoxCommand" />
          </Else>
        </If>
      </Commands>
    </Execution>

    <Execution>
      <ConditionExpression>
        <Command Name="SaveOnCloseMessageBoxCommand" Parameter="Yes" />
      </ConditionExpression>
      <Commands>
        <Command Name="SaveSequentialCommand" />
      </Commands>
    </Execution>
  </Executions>

</Form>

```

{% endcode %}

</details>

Вернемся в файл TemplateUserSettings.xml и добавим тэг `<Include>` с именем нового файла:

{% code title="TemplateUserSettings.xml" %}

```xml
  <Includes>
    <Include Path="_TemplateAppearance.xml" />
    <Include Path="_TemplateOnClose.xml" />
  </Includes>
```

{% endcode %}

Запустите приложение и проверьте отображение формы пользовательских настроек.

Переделайте файл настроек (TemplateSettings.xml) таким же образом. Не забудьте в файл \_TemplateAppearance.xml добавить цвет TabMouseOverBackColor.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://wfsys.gitbook.io/wt-practice/advanced/lesson_includes.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
