Compartilhar via


Building a WPF Application (WPF)

Windows Presentation Foundation (WPF)aplicativos podem ser criados como .NET Framework arquivos executáveis (. exe), bibliotecas (dll) ou uma combinação de ambos os tipos de módulos (assemblies). Este tópico discute como criar WPF aplicativos e descreve as principais etapas do processo de compilação.

Este tópico contém as seguintes seções.

  • Criando um aplicativo WPF
  • Pipeline de compilação do WPF
  • Incremental Build Support
  • Tópicos relacionados

Criando um aplicativo WPF

Um aplicativo WPF pode ser compilado das seguintes maneiras:

Pipeline de compilação do WPF

When a WPF project is built, the combination of language-specific and WPF-specific targets are invoked. The process of executing these targets is called the build pipeline, and the key steps are illustrated by the following figure.

Processo de compilação WPF

Pre-Build Initializations

Before building, MSBuild determines the location of important tools and libraries, including the following:

  • The .NET Framework.

  • The Windows SDK directories.

  • The location of WPF reference assemblies.

  • The property for the assembly search paths.

O primeiro local onde MSBuild procura por módulos (assemblies) é o diretório do assembly de referência (diretório Assemblies\Microsoft\Framework\v3.0\) (em inglês). During this step, the build process also initializes the various properties and item groups and performs any required cleanup work.

Resolving References

The build process locates and binds the assemblies required to build the application project. This logic is contained in the ResolveAssemblyReference task. All assemblies declared as Reference in the project file are provided to the task along with information on the search paths and metadata on assemblies already installed on the system. The task looks up assemblies and uses the installed assembly's metadata to filter out those core WPF assemblies that need not show up in the output manifests. This is done to avoid redundant information in the ClickOnce manifests. For example, since PresentationFramework.dll can be considered representative of an application built on and for the WPF and moreover since all WPF assemblies exist at the same location on every machine that has the .NET Framework installed, there is no need to include all information on all .NET Framework reference assemblies in the manifests.

Markup Compilation—Pass 1

In this step, XAML files are parsed and compiled so that the runtime does not spend time parsing XML and validating property values. O compilado XAML arquivo está indexado a pre para que, em tempo de execução, carregando-deve ser muito mais rápido que carregar um XAML arquivo.

During this step, the following activities take place for every XAML file that is a Page build item:

  1. The XAML file is parsed by the markup compiler.

  2. A compiled representation is created for that XAML and copied to the obj\Release folder.

  3. A CodeDOM representation of a new partial class is created and copied to the obj\Release folder.

Além disso, um arquivo de código específico do idioma é gerado para cada XAML arquivo. Por exemplo, para uma página de Page1.xaml em um Visual Basic o projeto, um Page1.g.vb é gerado; para uma página de Page1.xaml em um C# é gerado o projeto, um Page1.g.cs. ".g" o arquivo de nome indica o arquivo é gerado código que tenha uma declaração de classe parcial para o elemento de nível superior do arquivo de marcação (como Page ou Window). The class is declared with the partial modifier in C# (Extends in Visual Basic) to indicate there is another declaration for the class elsewhere, usually in the code-behind file Page1.xaml.cs.

The partial class extends from the appropriate base class (such as Page for a page) and implements the System.Windows.Markup.IComponentConnector interface. The IComponentConnector interface has methods to initialize a component and connect names and events on elements in its content. Consequently, the generated code file has a method implementation like the following:

public void InitializeComponent() {
    if (_contentLoaded) {
        return;
    }
    _contentLoaded = true;
    System.Uri resourceLocater = 
        new System.Uri(
            "window1.xaml", 
            System.UriKind.RelativeOrAbsolute);
    System.Windows.Application.LoadComponent(this, resourceLocater);
}
Public Sub InitializeComponent() _

    If _contentLoaded Then
        Return
    End If

    _contentLoaded = True
    Dim resourceLocater As System.Uri = _
        New System.Uri("mainwindow.xaml", System.UriKind.Relative)

    System.Windows.Application.LoadComponent(Me, resourceLocater)

End Sub

By default, markup compilation runs in the same AppDomain as the MSBuild engine. This provides significant performance gains. This behavior can be toggled with the AlwaysCompileMarkupFilesInSeparateDomain property. This has the advantage of unloading all reference assemblies by unloading the separate AppDomain.

Markup Compilation—Pass 2

Nem todos os XAML páginas são compiladas em durante o passo 1 de compilação da marcação. XAMLarquivos localmente definiu o tipo references (referências para tipos definidos no código em outro local no mesmo projeto) estão isentos de compilação neste momento. Isso ocorre porque esses tipos definidos localmente, existem apenas na origem e ainda não compilados. Para determinar isso, o analisador usa heurística que envolvem procurando itens tais como x:Name no arquivo de marcação. When such an instance is found, that markup file’s compilation is postponed until the code files have been compiled, after which, the second markup compilation pass processes these files.

File Classification

Os arquivos de saída do build processo coloca em diversos grupos de recursos com base em qual assembly do aplicativo serão colocados no. Em um aplicativo típico não localizado, todos os arquivos de dados são marcados como Resource são colocados no assembly principal (executável ou biblioteca). When UICulture is set in the project, all compiled XAML files and those resources specifically marked as language-specific are placed in the satellite resource assembly. Furthermore, all language-neutral resources are placed in the main assembly. In this step of the build process, that determination is made.

The ApplicationDefinition, Page, and Resource build actions in the project file can be augmented with the Localizable metadata (acceptable values are true and false), which dictates whether the file is language-specific or language-neutral.

Core Compilation

The core compile step involves compilation of code files. Isso é coordenado por lógica nos arquivos específicos do idioma destinos Microsoft.CSharp.targets e Microsoft.VisualBasic.targets. Se a heurística determinou que uma única passagem do compilador de marcação é suficiente, o assembly principal é gerado. No entanto, se um ou mais XAML arquivos no projeto tem referências aos tipos definidos localmente, em seguida, um arquivo temporário. dll é gerado para que os assemblies do final do aplicativo podem ser criados após a conclusão da segunda passagem da compilação da marcação.

Manifest Generation

At the end of the build process, after all the application assemblies and content files are ready, the ClickOnce manifests for the application are generated.

O arquivo de manifesto de implantação descreve o modelo de implantação: a versão atual, o comportamento de atualização e a identidade do Editor juntamente com a assinatura digital. This manifest is intended to be authored by administrators who handle deployment. The file extension is .xbap (for XAML browser applications (XBAPs)) and .application for installed applications. The former is dictated by the HostInBrowser project property and as a result the manifest identifies the application as browser-hosted.

The application manifest (an .exe.manifest file) describes the application assemblies and dependent libraries and lists permissions required by the application. This file is intended to be authored by the application developer. In order to launch a ClickOnce application, a user opens the application's deployment manifest file.

These manifest files are always created for XBAPs. For installed applications, they are not created unless the GenerateManifests property is specified in the project file with value true.

XBAPsobter duas permissões adicionais sobre essas permissões atribuídas a aplicativos típicos de zona de Internet: WebBrowserPermission and MediaPermission. The WPF build system declares those permissions in the application manifest.

Incremental Build Support

The WPF build system provides support for incremental builds. It is fairly intelligent about detecting changes made to markup or code, and it compiles only those artifacts affected by the change. The incremental build mechanism uses the following files:

  • An $(AssemblyName)_MarkupCompiler.Cache file to maintain current compiler state.

  • Um $(AssemblyName) o arquivo _MarkupCompiler.lref para o cache de XAML arquivos com referências aos tipos definidos localmente.

The following is a set of rules governing incremental build:

  • The file is the smallest unit at which the build system detects change. So, for a code file, the build system cannot tell if a type was changed or if code was added. The same holds for project files.

  • The incremental build mechanism must be cognizant that a XAML page either defines a class or uses other classes.

  • If Reference entries change, then recompile all pages.

  • If a code file changes, recompile all pages with locally defined type references.

  • If a XAML file changes:

    • Se XAML é declarada como Page no projeto: Se o XAML não têm referências de tipo definidas localmente, recompilar que XAML plus todos os XAML páginas com referências locais; Se o XAML tem referências locais, recompilar todos os XAML páginas com referências de local.

    • Se XAML é declarada como ApplicationDefinition no projeto: Recompilar tudo XAML páginas (motivo: cada XAML tem referência a uma Application tipo pode ter alterado).

  • If the project file declares a code file as application definition instead of a XAML file:

    • Check if the ApplicationClassName value in the project file has changed (is there a new application type?). If so, recompile the entire application.

    • Otherwise, recompile all XAML pages with local references.

  • Se mudar de um arquivo de projeto: Aplicar todas as regras precedentes e ver o que precisa ser recompilado. Alterações para as seguintes propriedades acionam uma recompilação completa: AssemblyName, IntermediateOutputPath, RootNamespace, and HostInBrowser.

The following recompile scenarios are possible:

  • The entire application is recompiled.

  • Somente os XAML arquivos localmente definiu referências de tipo são recompilados.

  • Nothing is recompiled (if nothing in the project has changed).

Consulte também

Conceitos

Implantar um aplicativo WPF (WPF)

Pack URIs in WPF

Recursos, conteúdo e arquivos de dados de aplicativos WPF

Outros recursos

Referência do WPF MSBuild

Histórico de alterações

Date

History

Motivo

Novembro de 2010

Exemplo de Visual Basic ausente adicionado.

Correção de bug de conteúdo.