Share via


Guia de início rápido: adicionando controles de página (HTML)

[ Este artigo destina-se aos desenvolvedores do Windows 8.x e do Windows Phone 8.x que escrevem aplicativos do Windows Runtime. Se você estiver desenvolvendo para o Windows 10, consulte documentação mais recente ]

Aprenda como criar e exibir objetos PageControl.

Pré-requisitos

Nós consideramos que você já saiba criar um aplicativo da Windows Store básico em JavaScript que use controles da Biblioteca do Windows para JavaScript. Para aprender a usar os controles WinJS, veja Guia de início rápido: adicionando controles e estilos WinJS.

Para criar um PageControl

Diferentemente de outros controles da Biblioteca do Windows para JavaScript, um PageControl não é instanciado diretamente. Em vez disso, você cria um PageControl chamando o método WinJS.UI.Pages.define e passado a ele o URI do arquivo HTML que define o PageControl e um objeto que define os membros do PageControl.

Veja a seguir um exemplo de definição de PageControl. Ele é composto de três arquivos: um arquivo HTML, um arquivo CSS e um arquivo JavaScript.


<!-- samplePageControl.html -->
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>samplePageControl</title>

    <!-- WinJS references -->
    <link href="/pages/samplePageControl.css" rel="stylesheet">
    <script src="/pages/samplePageControl.js"></script>
</head>
<body>
    <div class="samplePageControl">
        <p class="samplePageControl-text"><span data-win-bind="textContent: controlText">Message goes here</span>
        <button class="samplePageControl-button">Click me</button></p>
        <p>Page controls can also contain WinJS controls. They are activated automatically.</p>
        <div class="samplePageControl-toggle" data-win-control="WinJS.UI.ToggleSwitch"></div>
    </div>
</body>
</html>

/* samplePageControl.css */
.samplePageControl
{
    padding: 5px;
    border: 4px dashed #999999;
}

// samplePageControl.js
(function () {
    "use strict";

    var ControlConstructor = WinJS.UI.Pages.define("/pages/samplePageControl.html", {
        // This function is called after the page control contents
        // have been loaded, controls have been activated, and
        // the resulting elements have been parented to the DOM.
        ready: function (element, options) {
            options = options || {};
            this._data = WinJS.Binding.as({ controlText: options.controlText, message: options.message });

            // Data bind to the child tree to set the control text
            WinJS.Binding.processAll(element, this._data);

            // Hook up the click handler on our button
            WinJS.Utilities.query("button", element).listen("click",
                // JavaScript gotcha - use function.bind to make sure the this reference
                // inside the event callback points to the control object, not to
                // window
                this._onclick.bind(this));

            // WinJS controls can be manipulated via code in the page control too
            WinJS.Utilities.query(".samplePageControl-toggle", element).listen("change",
                this._ontoggle.bind(this));
        },

        // Getter/setter for the controlText property.
        controlText: {
            get: function () { return this._data.controlText; },
            set: function (value) { this._data.controlText = value; }
        },

        // Event handler that was wired up in the ready method
        _onclick: function (evt) {
            WinJS.log && WinJS.log(this._data.message + " button was clicked", "sample", "status");
        },

        // Event handler for when the toggle control switches
        _ontoggle: function (evt) {
            var toggleControl = evt.target.winControl;
            WinJS.log && WinJS.log(this._data.message + " toggle is now " + toggleControl.checked, "sample", "status");
        }
    });

    // The following lines expose this control constructor as a global.
    // This lets you use the control as a declarative control inside the
    // data-win-control attribute.

    WinJS.Namespace.define("Controls_PageControls", {
        SamplePageControl: ControlConstructor
    });
})();

Para criar um controle de Página no Microsoft Visual Studio, selecione Projeto > Adicionar Novo Item no menu principal e selecione Controle de Página.

Exibindo um PageControl

Depois que você definir o PageControl, haverá três maneiras de exibi-lo:

  • Use a função WinJS.UI.Pages.render.

    <div class="renderingPageControls-renderedControl"></div>
    
    // Render the page control via a call to WinJS.UI.Pages.render. This lets
    // you render a page control by referencing it via a url.
    var renderHost = element.querySelector(".renderingPageControls-renderedControl");
    WinJS.UI.Pages.render("/pages/SamplePageControl.html", renderHost, {
        controlText: "This control created by calling WinJS.UI.Pages.render",
        message: "Render control"
    }).done();
    
  • Exponha publicamente o construtor do objeto PageControl e use-o para criar o PageControl.

    <div class="renderingPageControls-createdProgrammatically"></div>
    
    // Render the page control by creating the control.
    var constructedHost = element.querySelector(".renderingPageControls-createdProgrammatically");
    new Controls_PageControls.SamplePageControl(constructedHost, {
        controlText: "This control created by calling the constructor directly",
        message: "Constructed control"
    });
    
  • Use a função WinJS.UI.Pages.get para obter um construtor para o PageControl.

  • Instancie o controle no HTML como se ele fosse um controle da Biblioteca do Windows para JavaScript (de fato, ele é). Para que isso funcione, é necessário expor publicamente o construtor do objeto PageControl.

    <div data-win-control="Controls_PageControls.SamplePageControl"
        data-win-options="{controlText: 'This was created declaratively', message: 'Declarative control' }">
    </div>
    
  • Use um HtmlControl para renderizar a página.

     <div class="renderingPageControls-htmlControl" data-win-control="WinJS.UI.HtmlControl"
        data-win-options="{uri: '/pages/samplePageControl.html',
        controlText: 'This was rendered via the HtmlControl', 
        message: 'HTML Control loaded control' }"></div>
    

Resumo e próximas etapas

Você aprendeu a criar e exibir objetos PageControl.

Para saber mais sobre como usar objetos PageControl, veja Guia de início rápido: usando a navegação de página única.