Поделиться через


Добавление панели инструментов ToolBar с командами (HTML)

[ Эта статья адресована разработчикам приложений среды выполнения Windows для Windows 8.x и Windows Phone 8.x. В случае разработки приложений для Windows 10 см. раздел последняя документация]

ToolBar является простым элементом управления, обеспечивающим масштабируемость команды. Он содержит action area, где команды незамедлительно доступны, и overflow area, где команды скрыты, но могут быть отображены по требованию пользователя. Элемент управления поддерживает адаптивное поведение, позволяя командам динамически перемещаться из основной в дополнительную область, если пространство ограничено. Панель инструментов ToolBar не ограничена отдельным местом в приложении и может находиться в различных местах, например на панели приложения Splitview, во всплывающем элементе Flyout и на холсте canvas.

Примечание  Следующие сценарии кодирования можно просмотреть более подробно на веб-сайте Try WinJS.

 

Создание панели инструментов ToolBar с декларативным добавлением команд

Команды можно добавить на панель инструментов ToolBar декларативно. В этом случае панель инструментов ToolBar имеет четыре основных и две дополнительных команды.

Dn972389.sample_toolbar(ru-ru,WIN.10).png

<div class="basicToolbar" data-win-control="WinJS.UI.ToolBar">
    <!-- Primary commands -->
    <button data-win-control="WinJS.UI.Command" data-win-options="{
            id:'cmdEdit',
            label:'edit',
            section:'primary',
            type:'button',
            icon: 'edit',
            onclick: Sample.outputCommand}"></button>
    <button data-win-control="WinJS.UI.Command" data-win-options="{
            id:'cmdDelete',
            label:'delete',
            section:'primary',
            type:'button',
            icon: 'delete',
            onclick: Sample.outputCommand}"></button>
    <button data-win-control="WinJS.UI.Command" data-win-options="{
            id:'cmdFavorite',
            label:'favorite',
            section:'primary',
            type:'toggle',
            icon: 'favorite',
            onclick: Sample.outputCommand}"></button>
    <button data-win-control="WinJS.UI.Command" data-win-options="{
            id:'cmdOpenWith',
            label:'open with',
            section:'primary',
            type:'button',
            icon: 'openfile',
            onclick: Sample.outputCommand}"></button>
    <button data-win-control="WinJS.UI.Command" data-win-options="{
            id:'cmdDownload',
            label:'download',
            section:'primary',
            type:'button',
            icon: 'download',
            onclick: Sample.outputCommand}"></button>

    <!-- Secondary command -->
    <button data-win-control="WinJS.UI.Command" data-win-options="{
            id:'cmdSettings',
            label:'settings',
            section:'secondary',
            type:'button',
            onclick: Sample.outputCommand}"></button>
    <button data-win-control="WinJS.UI.Command" data-win-options="{
            id:'cmdShare',
            label:'share',
            section:'secondary',
            type:'button',
            onclick: Sample.outputCommand}"></button>
</div>
<div class="status"></div>

WinJS.Namespace.define("Sample", {
    outputCommand: WinJS.UI.eventHandler(function (ev) {
        var status = document.querySelector(".status");
        var command = ev.currentTarget;
        if (command.winControl) {
            var label = command.winControl.label || command.winControl.icon || "button";
            var section = command.winControl.section || "";
            var msg = section + " command " + label + " was pressed";
            status.textContent = msg;
        }
    })
});

WinJS.UI.processAll();

Укажите группирование и порядок команд при раскрытии

Разработчики могут указать группирование и порядок команд при раскрытии в области переполнения, которая не соответствует визуальному порядку RTL. Это полезно, если пространство на экране ограничено. Элемент управления раскрывается с самого высокого до самого низкого значения. По умолчанию команды раскрываются справа налево. Но значение по умолчанию для приоритета не определен.

Dn972389.grouping_order_toolbar(ru-ru,WIN.10).png

<div class="groupingToolbar" data-win-control="WinJS.UI.ToolBar">
    <!-- Primary commands -->
    <button data-win-control="WinJS.UI.Command" data-win-options="{
            id:'cmdEdit',
            label:'edit',
            section:'primary',
            type:'button',
            icon: 'edit',
            priority:2,
            onclick: Sample.outputCommand}"></button>
    <button data-win-control="WinJS.UI.Command" data-win-options="{
            id:'cmdDelete',
            label:'delete',
            section:'primary',
            type:'button',
            icon: 'delete',
            priority:2,
            onclick: Sample.outputCommand}"></button>
    <hr data-win-control="WinJS.UI.Command" data-win-options="{type:'separator'}" />
    <button data-win-control="WinJS.UI.Command" data-win-options="{
            id:'cmdFavorite',
            label:'favorite',
            section:'primary',
            type:'toggle',
            icon: 'favorite',
            priority:3,
            onclick: Sample.outputCommand}"></button>
    <button data-win-control="WinJS.UI.Command" data-win-options="{
            id:'cmdOpenWith',
            label:'open with',
            section:'primary',
            type:'button',
            icon: 'openfile',
            priority:3,
            onclick: Sample.outputCommand}"></button>
    <button data-win-control="WinJS.UI.Command" data-win-options="{
            id:'cmdDownload',
            label:'download',
            section:'primary',
            type:'button',
            icon: 'download',
            priority:3,
            onclick: Sample.outputCommand}"></button>
    <button data-win-control="WinJS.UI.Command" data-win-options="{
            id:'cmdPin',
            label:'pin',
            section:'primary',
            type:'button',
            icon: 'pin',
            priority:3,
            onclick: Sample.outputCommand}"></button>
    <hr data-win-control="WinJS.UI.Command" data-win-options="{type:'separator'}" />
    <button data-win-control="WinJS.UI.Command" data-win-options="{
            id:'cmdZoom',
            label:'zoom',
            section:'primary',
            type:'button',
            icon: 'zoomin',
            priority:1,
            onclick: Sample.outputCommand}"></button>
    <button data-win-control="WinJS.UI.Command" data-win-options="{
            id:'cmdFullscreen',
            label:'full screen',
            section:'primary',
            type:'button',
            icon: 'fullscreen',
            priority:1,
            onclick: Sample.outputCommand}"></button>

    <!-- Secondary command -->
    <button data-win-control="WinJS.UI.Command" data-win-options="{
            id:'cmdSettings',
            label:'settings',
            section:'secondary',
            type:'button',
            onclick: Sample.outputCommand}"></button>
    <button data-win-control="WinJS.UI.Command" data-win-options="{
            id:'cmdShare',
            label:'share',
            section:'secondary',
            type:'button',
            onclick: Sample.outputCommand}"></button>
</div>
<div class="status"></div>
WinJS.Namespace.define("Sample", {
    outputCommand: WinJS.UI.eventHandler(function (ev) {
        var status = document.querySelector(".status");
        var command = ev.currentTarget;
        if (command.winControl) {
            var label = command.winControl.label || command.winControl.icon || "button";
            var section = command.winControl.section || "";
            var priority = command.winControl.priority;
            var msg = section + " command " + label + " with priority " + priority + " was pressed";
            status.textContent = msg;
        }
    })
});

WinJS.UI.processAll();

Показать несколько панелей инструментов ToolBar одновременно

Разработчики могут создать несколько панелей инструментов ToolBar и отобразить их одновременно.

Пример нескольких панелей инструментов

<div class="sampleToolBar" data-win-control="WinJS.UI.ToolBar">
    <!-- Primary commands -->
    <button data-win-control="WinJS.UI.Command" data-win-options="{
                id:'cmdEdit',
                label:'edit',
                section:'primary',
                type:'button',
                icon: 'edit',
                onclick: Sample.outputCommand}"></button>
    <button data-win-control="WinJS.UI.Command" data-win-options="{
                id:'cmdFavorite',
                label:'favorite',
                section:'primary',
                type:'toggle',
                icon: 'favorite',
                onclick: Sample.outputCommand}"></button>
    <button data-win-control="WinJS.UI.Command" data-win-options="{
                id:'cmdDelete',
                label:'delete',
                section:'primary',
                type:'button',
                icon: 'delete',
                onclick: Sample.outputCommand}"></button>

    <!-- Secondary commands -->
    <button data-win-control="WinJS.UI.Command" data-win-options="{
                id:'cmdSettings',
                label:'settings',
                section:'secondary',
                type:'button',
                onclick: Sample.outputCommand}"></button>
    <button data-win-control="WinJS.UI.Command" data-win-options="{
                id:'cmdShare',
                label:'share',
                section:'secondary',
                type:'button',
                onclick: Sample.outputCommand}"></button>
</div>

<div class="sampleToolBar2" data-win-control="WinJS.UI.ToolBar">
    <!-- Primary commands -->
    <button data-win-control="WinJS.UI.Command" data-win-options="{
                id:'cmdBold',
                section:'primary',
                type:'toggle',
                icon: 'bold',
                onclick: Sample.outputCommand}"></button>
    <button data-win-control="WinJS.UI.Command" data-win-options="{
                id:'cmdItalic',
                section:'primary',
                type:'toggle',
                icon: 'italic',
                onclick: Sample.outputCommand}"></button>
    <button data-win-control="WinJS.UI.Command" data-win-options="{
                id:'cmdUnderline',
                section:'primary',
                type:'toggle',
                icon: 'underline',
                onclick: Sample.outputCommand}"></button>
    <button data-win-control="WinJS.UI.Command" data-win-options="{
                id:'cmdEmoticon',
                section:'primary',
                type:'button',
                icon: 'emoji',
                onclick: Sample.outputCommand}"></button>

    <!-- Secondary commands -->
    <button data-win-control="WinJS.UI.Command" data-win-options="{
                id:'cmdSettings',
                label:'settings',
                section:'secondary',
                type:'button',
                onclick: Sample.outputCommand}"></button>
    <button data-win-control="WinJS.UI.Command" data-win-options="{
                id:'cmdShare',
                label:'share',
                section:'secondary',
                type:'button',
                onclick: Sample.outputCommand}"></button>
</div>
<div class="status"></div>
WinJS.Namespace.define("Sample", {
    outputCommand: WinJS.UI.eventHandler(function (ev) {
        var status = document.querySelector(".status");
        var command = ev.currentTarget;
        if (command.winControl) {
            var label = command.winControl.label || command.winControl.icon || "button";
            var section = command.winControl.section || "";
            var msg = section + " command " + label + " was pressed";
            status.textContent = msg;
        }
    })
});

WinJS.UI.processAll();

Создайте панель инструментов ToolBar с командами, добавленными с помощью WinJS.Binding.List

WinJS.Binding.List можно использовать для заполнения панели инструментов ToolBar командами с помощью свойства панели инструментов ToolBar data.

Пример панели инструментов с командами из списка привязки WinJS

<div class="imperativeToolBar" data-win-control="WinJS.UI.ToolBar"
     data-win-options="{data: Sample.commandList}"></div>
<div class="status"></div>
WinJS.Namespace.define("Sample", {
    commandList: null,
    outputCommand: WinJS.UI.eventHandler(function (ev) {
        var status = document.querySelector(".status");
        var command = ev.currentTarget;
        if (command.winControl) {
            var label = command.winControl.label || command.winControl.icon || "button";
            var section = command.winControl.section || "";
            var msg = section + " command " + label + " was pressed";
            status.textContent = msg;
        }
    })
});

var dataArray = [
    new WinJS.UI.Command(null, 
      { id: 'cmdEdit', label: 'edit', section: 'primary', type: 'button', icon: 'edit', onclick: Sample.outputCommand }),
    new WinJS.UI.Command(null, 
      { id: 'cmdDelete', label: 'delete', section: 'primary', type: 'button', icon: 'delete', onclick: Sample.outputCommand }),
    new WinJS.UI.Command(null, 
      { id: 'cmdFavorite', label: 'favorite', section: 'primary', type: 'toggle', icon: 'favorite', 
        onclick: Sample.outputCommand }),
    new WinJS.UI.Command(null, 
      { id: 'cmdOpenWith', label: 'open with', section: 'primary', type: 'button', icon: 'openfile', 
        onclick: Sample.outputCommand }),
    new WinJS.UI.Command(null, 
      { id: 'cmdDownload', label: 'download', section: 'primary', type: 'button', icon: 'download', 
        onclick: Sample.outputCommand }),
    new WinJS.UI.Command(null, 
      { id: 'cmdPin', label: 'pin', section: 'primary', type: 'button', icon: 'pin', onclick: Sample.outputCommand }),
    new WinJS.UI.Command(null, 
      { id: 'cmdZoom', label: 'zoom', section: 'primary', type: 'button', icon: 'zoomin', onclick: Sample.outputCommand }),
    new WinJS.UI.Command(null, 
      { id: 'cmdFullscreen', label: 'full screen', section: 'primary', type: 'button', icon: 'fullscreen', 
        onclick: Sample.outputCommand })
];

Sample.commandList = new WinJS.Binding.List(dataArray);

WinJS.UI.processAll();

Настройка панели инструментов ToolBar

Цвета по умолчанию панели инструментов ToolBar определяются или с помощью таблицы стилей ui-dark.css или ui-light.css в зависимости от того, какая таблица стилей загружена. Можно настроить цвета панели инструментов ToolBar, переопределив соответствующие правила CSS. В этом примере задается цвет фона панели инструментов ToolBar как прозрачный, а цвет фона области переполнения панели инструментов ToolBar настраивается в соответствии с фоновым изображением за ней.

Пример настроенной панели инструментов ToolBar

<div class="image">
    <img src="/pages/toolbar/images/Sunset.jpg" alt="" />
    <div data-win-control="WinJS.UI.ToolBar">
        <!-- Primary commands -->
        <button data-win-control="WinJS.UI.Command" data-win-options="{
                id:'cmdEdit',
                label:'edit',
                section:'primary',
                type:'button',
                icon: 'edit'}"></button>
        <button data-win-control="WinJS.UI.Command" data-win-options="{
                id:'cmdFavorite',
                label:'favorite',
                section:'primary',
                type:'toggle',
                icon: 'favorite'}"></button>
        <button data-win-control="WinJS.UI.Command" data-win-options="{
                id:'cmdDelete',
                label:'delete',
                section:'primary',
                type:'button',
                icon: 'delete'}"></button>
    </div>
</div>
/* Add your CSS here */
 body {
     background-color: rgb(112,112,112);
 }

 #content {
     text-align: center;
  overflow: hidden;
 }

 .image {
     position: relative;
     margin: auto;
     margin-top: 50px;
     margin-bottom:50px;
 }

 img { 
  max-width: 100%; 
 }

 .win-toolbar-actionarea {
  background: transparent;
 }

    .win-toolbar-overflowarea {
        background-color: rgb(74, 61, 78);
        border: 0;
    }
WinJS.UI.processAll();

Примечания

Эти и прочие примеры кодирования можно посмотреть на веб-сайте Try WinJS. Экспериментируйте с кодом, незамедлительно оценивая результаты.

Связанные разделы

WinJS.UI.Toolbar