Introdução ao WPF
Windows Presentation Foundation (WPF)é um sistema de apresentação de próxima geração para construção Windows aplicativos de cliente com visualmente impressionantes experiências de usuário. Com WPF, você pode criar uma ampla gama de autônomos e aplicativos hospedados em navegador. Um exemplo é o Aplicativo de exemplo Contoso Healthcare que é mostrado na figura a seguir.
O núcleo da WPF é um mecanismo de renderização independente de resolução e baseadas em vetor que é criado para tirar proveito do hardware de gráficos modernos. WPF estende o núcleo com um conjunto abrangente de recursos de desenvolvimento de aplicativos que incluem Extensible Application Markup Language (XAML), controles, ligação de dados, layout, 2-D e 3-D gráficos, animação, estilos, modelos, documentos, mídia, texto e tipografia. WPF está incluído na Microsoft .NET Framework, portanto, você pode criar aplicativos que incorporam outros elementos da .NET Framework biblioteca de classe.
This overview is intended for newcomers and covers the key capabilities and concepts of WPF. Experienced WPF developers seeking a review of WPF may also find this overview useful.
Observação
For new and updated WPF features in the .NET Framework 4, see O que há de novo na versão 4 do WPF.
Este tópico contém as seguintes seções.
- Programming with WPF
- Markup and Code-Behind
- Applications
- Controls
- Input and Commanding
- Layout
- Data Binding
- Graphics
- Animation
- Media
- Text and Typography
- Documents
- Customizing WPF Applications
- WPF Best Practices
- Summary
- Recommended Overviews and Samples
- Tópicos relacionados
Programming with WPF
WPFexiste como um subconjunto de .NET Framework tipos localizados em grande parte o System.Windows namespace. Se você criou anteriormente aplicativos com .NET Framework usando gerenciado tecnologias como ASP.NET e Windows Forms, o fundamentais WPF experiência em programação deve estar familiarizada; Você instanciar classes, definir propriedades, métodos de chamada e tratar eventos, utilizando o seu favorito .NET Framework programação idioma, como C# ou Visual Basic.
Para oferecer suporte a alguns dos mais poderosos WPF recursos e simplificar a experiência de programação, WPF inclui as construções de programação adicionais que aprimoram as propriedades e eventos: Propriedades de dependência e roteados eventos. Para obter mais informações sobre propriedades de dependência, consulte Visão geral sobre propriedades de dependência. Para obter mais informações sobre eventos roteados, consulte Visão geral sobre eventos roteados.
Markup and Code-Behind
WPF offers additional programming enhancements for Windows client application development. One obvious enhancement is the ability to develop an application using both markup and code-behind, an experience that ASP.NET developers should be familiar with. Você geralmente usa Extensible Application Markup Language (XAML) gerenciado de marcação para implementar a aparência de um aplicativo durante o uso de linguagens de programação (code-behind) para implementar o comportamento. This separation of appearance and behavior has the following benefits:
Development and maintenance costs are reduced because appearance-specific markup is not tightly coupled with behavior-specific code.
Development is more efficient because designers can implement an application's appearance simultaneously with developers who are implementing the application's behavior.
Várias ferramentas de design podem ser usadas para implementar e compartilhar XAML a marcação, para atingir os requisitos dos colaboradores de desenvolvimento do aplicativo; Microsoft Expression Blend fornece uma experiência que atenda os designers, enquanto Visual Studio 2005 os desenvolvedores de destinos.
Globalization and localization for WPF applications is greatly simplified (see Visão geral de globalização e localização do WPF).
The following is a brief introduction to WPF markup and code-behind. For more information on this programming model, see Visão geral do XAML (WPF) and Code-Behind e XAML no WPF.
Markup
XAMLé um XML-com base em linguagem de marcação que é usada para implementar a aparência de um aplicativo declarativamente. Ele é normalmente usado para criar janelas, caixas de diálogo, páginas e controles de usuário e preenchê-los com controles, formas e elementos gráficos.
The following example uses XAML to implement the appearance of a window that contains a single button.
<Window
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
Title="Window with Button"
Width="250" Height="100">
<!-- Add button to window -->
<Button Name="button">Click Me!</Button>
</Window>
Specifically, this XAML defines a window and a button by using the Window and Button elements, respectively. Cada elemento é configurado com atributos, como o Window do elemento atributo deTitle para especificar o texto de barra de título da janela. Em tempo de execução, WPF converte os elementos e atributos que são definidos na marcação para instâncias de WPF classes. For example, the Window element is converted to an instance of the Window class whose Title property is the value of the Title attribute.
A figura a seguir mostra a user interface (UI) que é definido pelo XAML o exemplo anterior.
For more information, see Visão geral do XAML (WPF).
Desde XAML é XML-com base, o UI Redigir com ele é montado em uma hierarquia de elementos aninhados, conhecido como um árvore de elemento. The element tree provides a logical and intuitive way to create and manage UIs. Para obter mais informações, consulte Árvores em WPF.
Code-Behind
The main behavior of an application is to implement the functionality that responds to user interactions, including handling events (for example, clicking a menu, tool bar, or button) and calling business logic and data access logic in response. In WPF, this behavior is generally implemented in code that is associated with markup. This type of code is known as code-behind. The following example shows the code-behind and updated markup from the previous example.
<Window
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.AWindow"
Title="Window with Button"
Width="250" Height="100">
<!-- Add button to window -->
<Button Name="button" Click="button_Click">Click Me!</Button>
</Window>
Namespace SDKSample
Partial Public Class AWindow
Inherits System.Windows.Window
Public Sub New()
' InitializeComponent call is required to merge the UI
' that is defined in markup with this class, including
' setting properties and registering event handlers
InitializeComponent()
End Sub
Private Sub button_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
' Show message box when button is clicked
MessageBox.Show("Hello, Windows Presentation Foundation!")
End Sub
End Class
End Namespace
using System.Windows; // Window, RoutedEventArgs, MessageBox
namespace SDKSample
{
public partial class AWindow : Window
{
public AWindow()
{
// InitializeComponent call is required to merge the UI
// that is defined in markup with this class, including
// setting properties and registering event handlers
InitializeComponent();
}
void button_Click(object sender, RoutedEventArgs e)
{
// Show message box when button is clicked
MessageBox.Show("Hello, Windows Presentation Foundation!");
}
}
}
In this example, the code-behind implements a class that derives from the Window class. O x:Class atributo é usado para associar a marcação com a classe de code-behind. InitializeComponenté chamada de construtor da classe code-behind para mesclar a interface do usuário é definida na marcação com a classe code-behind. (InitializeComponent é gerado para você quando seu aplicativo é criado, o motivo pelo qual você não precisa implementá-lo manualmente.) The combination of x:Class and InitializeComponent ensure that your implementation is correctly initialized whenever it is created. The code-behind class also implements an event handler for the button's Click event. When the button is clicked, the event handler shows a message box by calling the MessageBox.Show method.
The following figure shows the result when the button is clicked.
For more information, see Code-Behind e XAML no WPF.
Applications
.NET Framework, System.Windows, and markup and code-behind, constitute the foundation of the WPF application development experience. Additionally, WPF has comprehensive features for creating user experiences with rich content. Para compactar o conteúdo e entregá-lo aos usuários como "aplicativos", WPFfornece tipos e serviços que são conhecidos coletivamente como o o modelo de aplicativo. The application model supports the development of both standalone and browser-hosted applications.
Standalone Applications
For standalone applications, you can use the Window class to create windows and dialog boxes that are accessed from menu bars and tool bars. The following figure shows a standalone application with a main window and a dialog box.
Além disso, você pode usar o seguinte WPF caixas de diálogo: MessageBox, OpenFileDialog, SaveFileDialog, and PrintDialog.
For more information, see Visão geral do WPF do Windows.
Browser-Hosted Applications
Para aplicativos hospedados por navegador, conhecido como XAML browser applications (XBAPs), você pode criar páginas (Page) e funções de página (PageFunction<T>) que você pode navegar entre usando hiperlinks (Hyperlink classes). A figura a seguir mostra uma página em um XBAP que está hospedado em Internet Explorer 7.
WPFaplicativos podem ser hospedados em ambos os Microsoft Internet Explorer 6 e Internet Explorer 7. WPF offers the two following options for alternative navigation hosts:
Frame, to host islands of navigable content in either pages or windows.
NavigationWindow, to host navigable content in an entire window.
For more information, see Visão geral de navegação.
The Application Class
Ambos XBAPs e aplicativos autônomos são geralmente complexos o suficiente para solicitar serviços adicionais escopa da aplicação, incluindo gerenciamento de inicialização e o tempo de vida, propriedades compartilhadas e recursos compartilhados. O Application classe encapsula esses serviços e muito mais, e pode ser implementado usando-se apenas XAML, conforme mostrado no exemplo a seguir.
<Application
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
StartupUri="MainWindow.xaml" />
Essa marcação é o definição de aplicativo para um aplicativo autônomo e instrui WPF para criar um Application objeto que abre automaticamente MainWindow quando o aplicativo é iniciado.
A key concept to understand about Application is that it provides a common platform of support for both standalone and browser-hosted applications. For example, the preceding XAML could be used by a browser-hosted application to automatically navigate to a page when an XBAP is started, as shown in the following example.
<Application
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
StartupUri="HomePage.xaml" />
For more information, see Visão Geral do Gerenciamento de Aplicativo.
Security
Porque XBAPs são hospedados em um navegador, a segurança é importante. Em particular, uma proteção de segurança de confiança parcial é usada por XBAPs para impor restrições que são menores ou iguais às restrições impostas em HTML-com base em aplicativos. Além disso, cada HTML que é seguro executar a partir do recurso XBAPs em confiança parcial foi testado usando um processo de segurança abrangente, detalhado na Estratégia de segurança do WPF - Engenharia de Segurança.
Ainda assim, a maioria dos WPF recursos podem ser executados com segurança em XBAPs, conforme descrito na WPF Partial Trust Security.
Controls
The user experiences that are delivered by the application model are constructed controls. Em WPF, "controle" é um termo que se aplica a uma categoria de WPF classes que são hospedados em uma janela ou em uma página, têm um user interface (UI)e implementar algumas comportamento.
For more information, see Controles.
Controles do WPF pela função
The built-in WPF controls are listed here.
Botões: Button and RepeatButton.
Seleção e exibição de data: Calendar and DatePicker.
Caixas de diálogo: OpenFileDialog, PrintDialog, and SaveFileDialog.
Tinta digital: InkCanvas and InkPresenter.
Documentos: DocumentViewer, FlowDocumentPageViewer, FlowDocumentReader, FlowDocumentScrollViewer, and StickyNoteControl.
Entrada: TextBox, RichTextBox, and PasswordBox.
Layout: Border, BulletDecorator, Canvas, DockPanel, Expander, Grid, GridView, GridSplitter, GroupBox, Panel, ResizeGrip, Separator, ScrollBar, ScrollViewer, StackPanel, Thumb, Viewbox, VirtualizingStackPanel, Window, and WrapPanel.
Mídia: Image, MediaElement, and SoundPlayerAction.
Menus: ContextMenu, Menu, and ToolBar.
Navegação: Frame, Hyperlink, Page, NavigationWindow, and TabControl.
Seleção: CheckBox, ComboBox, ListBox, RadioButton, and Slider.
Informações de usuário: AccessText, Label, Popup, ProgressBar, StatusBar, TextBlock, and ToolTip.
Input and Commanding
Controls most often detect and respond to user input. The WPF input system uses both direct and routed events to support text input, focus management, and mouse positioning. For more information, see Input Overview.
Aplicativos geralmente têm requisitos complexos de entrada. WPFFornece um sistema de comando que separa as ações de entrada do usuário do código que responde a essas ações. Para obter mais informações, consulte Visão geral de Comando.
Layout
When you create a UI, you arrange your controls by location and size to form a layout. A key requirement of any layout is to adapt to changes in window size and display settings. Em vez de forçá-lo a escrever o código para adaptar um layout nessas circunstâncias, WPF fornece um sistema de layout de primeira classe e extensível para você.
The cornerstone of the layout system is relative positioning, which increases the ability to adapt to changing window and display conditions. In addition, the layout system manages the negotiation between controls to determine the layout. A negociação é um processo de duas etapas: primeiro, de um controle pai informa quais local e tamanho requer; segundo, o pai informa o controle que ele pode ter de espaço.
O sistema de layout é exposto a controles de filho através da base de WPF classes. Para layouts comuns como, por exemplo, grades, empilhamento e encaixe, WPF inclui vários controles de layout:
Canvas: Controles filho fornecem seu próprio layout.
DockPanel: Controles filhos são alinhados às bordas do painel.
Grid: Controles filho são posicionados por linhas e colunas.
StackPanel: Controles filhos são empilhadas vertical ou horizontalmente.
VirtualizingStackPanel: Controles filhos são virtualizados e organizados em uma única linha que é orientada horizontal ou verticalmente.
WrapPanel: Controles filho são posicionados na ordem da esquerda para direita e empacotados para a próxima linha quando há mais controles na linha atual do que o espaço permitido.
The following example uses a DockPanel to lay out several TextBox controls.
<Window
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.LayoutWindow"
Title="Layout with the DockPanel" Height="143" Width="319">
<!--DockPanel to layout four text boxes-->
<DockPanel>
<TextBox DockPanel.Dock="Top">Dock = "Top"</TextBox>
<TextBox DockPanel.Dock="Bottom">Dock = "Bottom"</TextBox>
<TextBox DockPanel.Dock="Left">Dock = "Left"</TextBox>
<TextBox Background="White">This TextBox "fills" the remaining space.</TextBox>
</DockPanel>
</Window>
The DockPanel allows the child TextBox controls to tell it how to arrange them. To do this, the DockPanel implements a Dock property that is exposed to the child controls to allow each of them to specify a dock style.
Observação
Uma propriedade que é implementada por um controle pai para uso por controles filho é um WPF construção chamada um anexado a propriedade (consulte Attached Properties Overview).
The following figure shows the result of the XAML markup in the preceding example.
For more information, see Sistema de layout. Para uma amostra de Introdução, consulte Exemplo de galeria de Layout do WPF.
Data Binding
Most applications are created to provide users with the means to view and edit data. For WPF applications, the work of storing and accessing data is already provided for by technologies such as Microsoft SQL Server and ADO.NET. After the data is accessed and loaded into an application's managed objects, the hard work for WPF applications begins. Essentially, this involves two things:
Copying the data from the managed objects into controls, where the data can be displayed and edited.
Ensuring that changes made to data by using controls are copied back to the managed objects.
Para simplificar o desenvolvimento de aplicativos, WPF fornece um mecanismo de ligação de dados automaticamente, execute estas etapas. A unidade principal do mecanismo de ligação de dados é o Binding classe, cujo trabalho é vincular um controle (o destino de vinculação) um objeto de dados (a origem de ligação). This relationship is illustrated by the following figure.
The following example demonstrates how to bind a TextBox to an instance of a custom Person object. The Person implementation is shown in the following code.
Namespace SDKSample
Class Person
Private _name As String = "No Name"
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
End Class
End Namespace
namespace SDKSample
{
class Person
{
string name = "No Name";
public string Name
{
get { return name; }
set { name = value; }
}
}
}
The following markup binds the TextBox to an instance of a custom Person object.
<Window
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.DataBindingWindow">
...
<!-- Bind the TextBox to the data source (TextBox.Text to Person.Name) -->
<TextBox Name="personNameTextBox" Text="{Binding Path=Name}" />
...
</Window>
Imports System.Windows ' Window
Namespace SDKSample
Partial Public Class DataBindingWindow
Inherits Window
Public Sub New()
InitializeComponent()
' Create Person data source
Dim person As Person = New Person()
' Make data source available for binding
Me.DataContext = person
End Sub
End Class
End Namespace
using System.Windows; // Window
namespace SDKSample
{
public partial class DataBindingWindow : Window
{
public DataBindingWindow()
{
InitializeComponent();
// Create Person data source
Person person = new Person();
// Make data source available for binding
this.DataContext = person;
}
}
}
In this example, the Person class is instantiated in code-behind and is set as the data context for the DataBindingWindow. In markup, the Text property of the TextBox is bound to the Person.Name property (using the "{Binding ... }" XAML syntax). This XAML tells WPF to bind the TextBox control to the Person object that is stored in the DataContext property of the window.
O WPF o mecanismo de ligação de dados fornece suporte adicional, que inclui a validação, classificação, filtragem e agrupamento. Além disso, a ligação de dados suporta o uso de modelos de dados para criar personalizado UI para os dados vinculados quando o UI exibida pelo padrão WPF controles não é apropriado.
For more information, see Revisão de Associação de Dados. Para uma amostra de Introdução, consulte A demonstração de ligação de dados.
Graphics
WPF introduces an extensive, scalable, and flexible set of graphics features that have the following benefits:
Resolution-independent and device-independent graphics. The basic unit of measurement in the WPF graphics system is the device independent pixel, which is 1/96th of an inch, regardless of actual screen resolution, and provides the foundation for resolution-independent and device-independent rendering. Each device-independent pixel automatically scales to match the dots-per-inch (dpi) setting of the system it renders on.
Improved precision. O WPF sistema de coordenadas é medido com números de ponto flutuante de precisão dupla, em vez de single-precision. As transformações e os valores de opacidade também são expressos como precisão dupla. WPFtambém oferece suporte a uma gama de cores (scRGB) e fornece suporte integrado para o gerenciamento de entradas de diferentes espaços de cores.
Suporte de animação e elementos gráficos avançado. WPFsimplifica a programação de gráficos por Gerenciando cenas de animação para você; não é necessário se preocupar sobre processamento de cena, loops de processamento e interpolação bilinear. Additionally, WPF provides hit-testing support and full alpha-compositing support.
Hardware acceleration. The WPF graphics system takes advantage of graphics hardware to minimize CPU usage.
2-D Shapes
WPF provides a library of common vector-drawn 2-D shapes, such as the rectangles and ellipses that are shown in the following illustration.
An interesting capability of shapes is that they are not just for display; shapes implement many of the features that you expect from controls, including keyboard and mouse input. The following example shows the MouseUp event of an Ellipse being handled.
<Window
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.EllipseEventHandlingWindow"
Title="Click the Ellipse">
<Ellipse Name="clickableEllipse" Fill="Blue" MouseUp="clickableEllipse_MouseUp" />
</Window>
Imports System.Windows ' Window, MessageBox
Imports System.Windows.Input ' MouseButtonEventArgs
Namespace SDKSample
Public Class EllipseEventHandlingWindow
Inherits Window
Public Sub New()
InitializeComponent()
End Sub
Private Sub clickableEllipse_MouseUp(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
MessageBox.Show("You clicked the ellipse!")
End Sub
End Class
End Namespace
using System.Windows; // Window, MessageBox
using System.Windows.Input; // MouseButtonEventHandler
namespace SDKSample
{
public partial class EllipseEventHandlingWindow : Window
{
public EllipseEventHandlingWindow()
{
InitializeComponent();
}
void clickableEllipse_MouseUp(object sender, MouseButtonEventArgs e)
{
// Display a message
MessageBox.Show("You clicked the ellipse!");
}
}
}
The following figure shows what is produced by the preceding code.
For more information, see Visão geral de Formas e Desenho básico no WPF. Para uma amostra de Introdução, consulte Exemplo de elementos de forma.
2-D Geometries
The 2-D shapes provided by WPF cover the standard set of basic shapes. No entanto, talvez você precise criar formas personalizadas para facilitar o design de um personalizado UI. For this purpose, WPF provides geometries. The following figure demonstrates the use of geometries to create a custom shape that can be drawn directly, used as a brush, or used to clip other shapes and controls.
Path objects can be used to draw closed or open shapes, multiple shapes, and even curved shapes.
Geometryobjetos podem ser usados para recorte, teste de impacto e tornando os dados gráficos 2D.
For more information, see Visão Geral de Geometria. Para uma amostra de Introdução, consulte A amostra de geometrias.
2-D Effects
Um subconjunto de WPF 2-D recursos inclui efeitos visuais, como, por exemplo, gradientes, bitmaps, desenhos, pintura com vídeos, rotação, dimensionamento, e inclinação. Esses são alcançados com pincéis; a figura a seguir mostra alguns exemplos.
For more information, see WPF Brushes Overview. Para uma amostra de Introdução, consulte A amostra de pincéis.
3-D Rendering
WPFtambém inclui 3-D recursos de processamento que se integram com 2-D gráficos para permitir a criação de mais interessantes e interessante UIs. Por exemplo, a seguinte figura mostra 2-D imagens processadas em 3-D formas.
For more information, see Visão geral de elementos gráficos 3D. Para uma amostra de Introdução, consulte Exemplo de sólidos 3D.
Animation
WPFpermite animação suporte que você faça controles aumentar, agite, rotação e desaparecer, para criar interessante página transições e muito mais. Você pode animar mais WPF classes, até mesmo classes personalizadas. The following figure shows a simple animation in action.
For more information, see Revisão de Animação. Para uma amostra de Introdução, consulte Galeria de exemplo de animação.
Media
One way to convey rich content is through the use of audiovisual media. WPF provides special support for images, video, and audio.
Images
As imagens são comuns à maioria dos aplicativos, e WPF fornece várias maneiras de usá-los. The following figure shows a UI with a list box that contains thumbnail images. When a thumbnail is selected, the image is shown full-size.
For more information, see Visão geral sobre imagens.
Video and Audio
The MediaElement control is capable of playing both video and audio, and it is flexible enough to be the basis for a custom media player. The following XAML markup implements a media player.
<MediaElement
Name="myMediaElement"
Source="media/wpf.wmv"
LoadedBehavior="Manual"
Width="350" Height="250" />
The window in the following figure shows the MediaElement control in action.
For more information, see Graphics and Multimedia.
Text and Typography
Para facilitar o processamento de texto de alta qualidade, WPF oferece os seguintes recursos:
OpenType font support.
ClearType enhancements.
High performance that takes advantage of hardware acceleration.
Integration of text with media, graphics, and animation.
International font support and fallback mechanisms.
As a demonstration of text integration with graphics, the following figure shows the application of text decorations.
For more information, see Tipologia no WPF.
Documents
WPFtem suporte nativo para trabalhar com três tipos de documentos: o fluxo de documentos, fixo de documentos, e XML Paper Specification (XPS) documentos. WPFtambém fornece serviços para criar, exibir, gerenciar, anotar, empacotar e imprimir documentos.
Flow Documents
Flow documents are designed to optimize viewing and readability by dynamically adjusting and reflowing content when window size and display settings change. O seguinte XAML marcação mostra a definição de um FlowDocument.
<FlowDocument xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Paragraph FontSize="18" FontWeight="Bold">Flow Document</Paragraph>
<Paragraph>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy
nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi
enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis
nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure.
</Paragraph>
...
</FlowDocument>
The following example demonstrates how to load a flow document into a FlowDocumentReader for viewing, searching, and printing.
<Window
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.FlowDocumentReaderWindow"
Title="Flow Document Reader">
<FlowDocumentReader Name="flowDocumentReader" />
</Window>
Imports System.Windows 'Window
Imports System.Windows.Documents 'FlowDocument
Imports System.IO 'FileStream, FileMode
Imports System.Windows.Markup 'XamlReader
Namespace SDKSample
Public Class FlowDocumentReaderWindow
Inherits Window
Public Sub New()
Me.InitializeComponent()
Using stream1 As FileStream = New FileStream("AFlowDocument.xaml", _
FileMode.Open, FileAccess.Read)
Dim document1 As FlowDocument = _
TryCast(XamlReader.Load(stream1), FlowDocument)
Me.flowDocumentReader.Document = document1
End Using
End Sub
End Class
End Namespace
using System.Windows; // Window
using System.Windows.Documents; // FlowDocument
using System.IO; // FileStream, FileMode
using System.Windows.Markup; // XamlReader
namespace SDKSample
{
public partial class FlowDocumentReaderWindow : System.Windows.Window
{
public FlowDocumentReaderWindow()
{
InitializeComponent();
// Open the file that contains the FlowDocument
using (FileStream xamlFile = new FileStream("AFlowDocument.xaml",
FileMode.Open, FileAccess.Read))
{
// Parse the file with the XamlReader.Load method
FlowDocument content = XamlReader.Load(xamlFile) as FlowDocument;
// Set the Document property to the parsed FlowDocument object
this.flowDocumentReader.Document = content;
}
}
}
}
The following example shows the result.
For more information, see Flow Document Overview.
Fixed Documents
Fixed documents are intended for applications that require a precise "what you see is what you get" (WYSIWYG) presentation, particularly with respect to printing. Typical uses for fixed documents include desktop publishing, word processing, and form layout, where adherence to the original page design is critical.
Fixed documents maintain the precise arrangement of their content in a device-independent manner. For example, a fixed document that is displayed on a 96 dots-per-inch (dpi) display appears the same as when it is printed to either a 600 dpi laser printer or a 4800 dpi photo typesetter. The layout remains the same in all cases, although the document's quality varies depending on the capabilities of each device.
For more information, see Documentos no WPF.
XPS Documents
XML Paper Specification (XPS)criar documentos WPFdo fixo documentos. XPSdocumentos são descritos com um XML-com base no esquema é essencialmente uma representação paginada papel eletrônico. XPSé um formato de documento aberto, de plataforma híbrida é projetado para facilitar a criação, compartilhamento, impressão e arquivamento de documentos paginados. Important features of the XPS technology include the following:
Empacotamento de XPS documentos como ZipPackage arquivos estão de acordo com o Open Packaging Conventions (OPC).
Hosting in both standalone and browser-based applications.
Manual generation and manipulation of XPS documents from WPF applications.
High-fidelity rendering by targeting maximum output device quality.
Windows Vista print spooling.
Direct routing of documents to XPS-compatible printers.
UI integration with DocumentViewer.
The following figure shows an XPS document that is displayed by a DocumentViewer.
DocumentViewer also allows users to change the view, search, and print XPS documents.
For more information, see Documentos no WPF.
Annotations
Annotations are notes or comments that are added to documents to flag information or to highlight items of interest for later reference. Although writing notes on printed documents is easy, the ability to "write" notes on electronic documents is often limited or unavailable. In WPF, however, an annotations system is provided to support sticky notes and highlights. Additionally, these annotations can be applied to documents hosted in the DocumentViewer control, as shown in the following figure.
For more information, see Visão geral de Anotações.
Packaging
O WPF System.IO.Packaging APIs permitem que seus aplicativos organizar dados, conteúdo e recursos em um único, portátil, fácil-distribuir e acesso fácil ZIP documentos. Digital signatures can be included to authenticate items that are contained in a package and to verify that the signed item was not tampered with or modified. You can also encrypt packages by using rights management in order to restrict access to protected information.
For more information, see Documentos no WPF.
Printing
O .NET Framework inclui um subsistema de impressão que WPF amplia o suporte para o controle do sistema de impressão Avançado. Printing enhancements include the following:
Real-time installation of remote print servers and queues.
Dynamic discovery of printer capabilities.
Dynamic setting of printer options.
Print job rerouting and reprioritizing.
XPS documents also have a key performance enhancement. The existing Microsoft Windows Graphics Device Interface (GDI) print path typically requires two conversions:
The first conversion of a document into a print processor format, such as Enhanced Metafile (EMF).
A second conversion into the page description language of the printer, such as Printer Control Language (PCL) or PostScript.
No entanto, XPS documentos evitar essas conversões porque um componente da XPS formato de arquivo é uma linguagem de processador de impressão e uma linguagem de descrição de página. This support helps to reduce both spool file size and networked printer loads.
For more information, see Visão Geral de Impressão.
Customizing WPF Applications
Até este ponto, você viu o núcleo WPF blocos de construção para o desenvolvimento de aplicativos. You use the application model to host and deliver application content, which consists mainly of controls. Para simplificar a disposição dos controles em um UI, e para garantir que a organização é mantida no caso de alterações de tamanho de janela e exibir as configurações, use o WPF sistema de layout. Como a maioria dos aplicativos permitem que os usuários interajam com dados, usar a ligação de dados para reduzir o trabalho de integração de sua UI com dados. Para melhorar a aparência visual do seu aplicativo, você usar o intervalo abrangente de elementos gráficos, animação e mídia de suporte fornecido pela WPF. Finalmente, se seu aplicativo opera sobre o texto e documentos, você pode usar o WPF texto, tipografia, documento, anotação, empacotamento e a impressão de recursos.
Often, though, the basics are not enough for creating and managing a truly distinct and visually stunning user experience. O padrão WPF controles não podem integrar com a aparência desejada de seu aplicativo. Data may not be displayed in the most effective way. Experiência geral do aplicativo não seja ideal para o padrão look and feel of Windows temas. In many ways, a presentation technology needs visual extensibility as much as any other kind of extensibility.
For this reason, WPF provides a variety of mechanisms for creating unique user experiences, including a rich content model for controls, triggers, control and data templates, styles, UI resources, and themes and skins.
Content Model
The main purpose of a majority of the WPF controls is to display content. In WPF, the type and number of items that can constitute the content of a control is referred to as the control's content model. Some controls can contain a single item and type of content; for example, the content of a TextBox is a string value that is assigned to the Text property. The following example sets the content of a TextBox.
<Window
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.TextBoxContentWindow"
Title="TextBox Content">
...
<TextBox Text="This is the content of a TextBox." />
...
</Window>
The following figure shows the result.
Other controls, however, can contain multiple items of different types of content; the content of a Button, specified by the Content property, can contain a variety of items including layout controls, text, images, and shapes. The following example shows a Button with content that includes a DockPanel, a Label, a Border, and a MediaElement.
<Window
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.ButtonContentWindow"
Title="Button Content">
...
<Button Margin="20">
<!-- Button Content -->
<DockPanel Width="200" Height="180">
<Label DockPanel.Dock="Top" HorizontalAlignment="Center">Click Me!</Label>
<Border Background="Black" BorderBrush="Yellow" BorderThickness="2"
CornerRadius="2" Margin="5">
<MediaElement Source="media/wpf.wmv" Stretch="Fill" />
</Border>
</DockPanel>
</Button>
...
</Window>
The following figure shows the content of this button.
For more information on the kinds of content that is supported by various controls, see Modelo de conteúdo WPF.
Triggers
Although the main purpose of XAML markup is to implement an application's appearance, you can also use XAML to implement some aspects of an application's behavior. One example is the use of triggers to change an application's appearance based on user interactions. Para obter mais informações, consulte "Disparadores" em Styling and Templating.
Control Templates
O padrão UIs para WPF controles geralmente são construídos a partir de outros controles e formas. Por exemplo, um Button é composto de dois ButtonChrome e ContentPresenter controles. The ButtonChrome provides the standard button appearance, while the ContentPresenter displays the button's content, as specified by the Content property.
Sometimes the default appearance of a control may be incongruent with the overall appearance of an application. In this case, you can use a ControlTemplate to change the appearance of the control's UI without changing its content and behavior.
For example, the following example shows how to change the appearance of a Button by using a ControlTemplate.
<Window
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.ControlTemplateButtonWindow"
Title="Button with Control Template" Height="158" Width="290">
<!-- Button using an ellipse -->
<Button Content="Click Me!" Click="button_Click">
<Button.Template>
<ControlTemplate TargetType="{x:Type Button}">
<Grid Margin="5">
<Ellipse Stroke="DarkBlue" StrokeThickness="2">
<Ellipse.Fill>
<RadialGradientBrush Center="0.3,0.2" RadiusX="0.5" RadiusY="0.5">
<GradientStop Color="Azure" Offset="0.1" />
<GradientStop Color="CornflowerBlue" Offset="1.1" />
</RadialGradientBrush>
</Ellipse.Fill>
</Ellipse>
<ContentPresenter Name="content" HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
</Button.Template>
</Button>
</Window>
Imports System.Windows ' Window, RoutedEventArgs, MessageBox
Namespace SDKSample
Public Class ControlTemplateButtonWindow
Inherits Window
Public Sub New()
InitializeComponent()
End Sub
Private Sub button_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
MessageBox.Show("Hello, Windows Presentation Foundation!")
End Sub
End Class
End Namespace
using System.Windows; // Window, RoutedEventArgs, MessageBox
namespace SDKSample
{
public partial class ControlTemplateButtonWindow : Window
{
public ControlTemplateButtonWindow()
{
InitializeComponent();
}
void button_Click(object sender, RoutedEventArgs e)
{
// Show message box when button is clicked
MessageBox.Show("Hello, Windows Presentation Foundation!");
}
}
}
In this example, the default button UI has been replaced with an Ellipse that has a dark blue border and is filled using a RadialGradientBrush. O ContentPresenter controle exibe o conteúdo de Button, "Click Me"! When the Button is clicked, the Click event is still raised as part of the Button control's default behavior. The result is shown in the following figure.
For more information, see ControlTemplate. Para uma amostra de Introdução, consulte de estilo com amostra de ControlTemplates.
Data Templates
Whereas a control template lets you specify the appearance of a control, a data template lets you specify the appearance of a control's content. Data templates are frequently used to enhance how bound data is displayed. The following figure shows the default appearance for a ListBox that is bound to a collection of Task objects, where each task has a name, description, and priority.
The default appearance is what you would expect from a ListBox. However, the default appearance of each task contains only the task name. To show the task name, description, and priority, the default appearance of the ListBox control's bound list items must be changed by using a DataTemplate. O seguinte XAML define como um DataTemplate, que é aplicado a cada tarefa usando o ItemTemplate atributo.
<Window
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.DataTemplateWindow"
Title="With a Data Template">
...
<Window.Resources>
<!-- Data Template (applied to each bound task item in the task collection) -->
<DataTemplate x:Key="myTaskTemplate">
<Border Name="border" BorderBrush="DarkSlateBlue" BorderThickness="2"
CornerRadius="2" Padding="5" Margin="5">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Padding="0,0,5,0" Text="Task Name:"/>
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Path=TaskName}"/>
<TextBlock Grid.Row="1" Grid.Column="0" Padding="0,0,5,0" Text="Description:"/>
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Path=Description}"/>
<TextBlock Grid.Row="2" Grid.Column="0" Padding="0,0,5,0" Text="Priority:"/>
<TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding Path=Priority}"/>
</Grid>
</Border>
</DataTemplate>
</Window.Resources>
...
<!-- UI -->
<DockPanel>
<!-- Title -->
<Label DockPanel.Dock="Top" FontSize="18" Margin="5" Content="My Task List:"/>
<!-- Data template is specified by the ItemTemplate attribute -->
<ListBox
ItemsSource="{Binding}"
ItemTemplate="{StaticResource myTaskTemplate}"
HorizontalContentAlignment="Stretch"
IsSynchronizedWithCurrentItem="True"
Margin="5,0,5,5" />
</DockPanel>
...
</Window>
The following figure shows the effect of this code.
Note that the ListBox has retained its behavior and overall appearance; only the appearance of the content being displayed by the list box has changed.
For more information, see Visão geral sobre Templating de dados. Para uma amostra de Introdução, consulte Introdução ao exemplo de modelagem de dados.
Styles
Os estilos permitem que os desenvolvedores e designers padronizar em uma aparência específica para seu produto. WPFFornece um modelo de estilo de alta segurança, a base da qual é o Style elemento. The following example creates a style that sets the background color for every Button on a window to Orange.
<Window
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.StyleWindow"
Title="Styles">
...
<!-- Style that will be applied to all buttons -->
<Style TargetType="{x:Type Button}">
<Setter Property="Background" Value="Orange" />
<Setter Property="BorderBrush" Value="Crimson" />
<Setter Property="FontSize" Value="20" />
<Setter Property="FontWeight" Value="Bold" />
<Setter Property="Margin" Value="5" />
</Style>
...
<!-- This button will have the style applied to it -->
<Button>Click Me!</Button>
<!-- This label will not have the style applied to it -->
<Label>Don't Click Me!</Label>
<!-- This button will have the style applied to it -->
<Button>Click Me!</Button>
...
</Window>
Because this style targets all Button controls, the style is automatically applied to all the buttons in the window, as shown in the following figure.
For more information, see Styling and Templating. Para uma amostra de Introdução, consulte Introdução aos estilos e modelos de exemplo.
Resources
Controls in an application should share the same appearance, which can include anything from fonts and background colors to control templates, data templates, and styles. Você pode usar WPFdo suporte para user interface (UI) recursos para encapsular esses recursos em um único local para reutilização.
The following example defines a common background color that is shared by a Button and a Label.
<Window
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.ResourcesWindow"
Title="Resources Window">
<!-- Define window-scoped background color resource -->
<Window.Resources>
<SolidColorBrush x:Key="defaultBackground" Color="Red" />
</Window.Resources>
...
<!-- Button background is defined by window-scoped resource -->
<Button Background="{StaticResource defaultBackground}">One Button</Button>
<!-- Label background is defined by window-scoped resource -->
<Label Background="{StaticResource defaultBackground}">One Label</Label>
...
</Window>
This example implements a background color resource by using the Window.Resources property element. This resource is available to all children of the Window. There are a variety of resource scopes, including the following, listed in the order in which they are resolved:
An individual control (using the inherited FrameworkElement.Resources property).
A Window or a Page (also using the inherited FrameworkElement.Resources property).
An Application (using the Application.Resources property).
The variety of scopes gives you flexibility with respect to the way in which you define and share your resources.
As an alternative to directly associating your resources with a particular scope, you can package one or more resources by using a separate ResourceDictionary that can be referenced in other parts of an application. For example, the following example defines a default background color in a resource dictionary.
<ResourceDictionary
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml">
<!-- Define background color resource -->
<SolidColorBrush x:Key="defaultBackground" Color="Red" />
<!-- Define other resources -->
...
</ResourceDictionary>
The following example references the resource dictionary defined in the previous example so that it is shared across an application.
<Application
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.App">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="BackgroundColorResources.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
...
</Application>
Resources and resource dictionaries are the foundation of WPF support for themes and skins.
For more information, see Visão geral sobre Recursos.
Themes and Skins
De uma perspectiva visual, um tema define a aparência global de Windows e os aplicativos executados dentro do proprietário. Windowsvem com vários temas. Por exemplo, Microsoft Windows XP vem com o Windows XP e Windows Classic temas, enquanto Windows Vista vem com o Windows Vista e Windows Classic temas. The appearance that is defined by a theme defines the default appearance for a WPF application. WPF, no entanto, não se integra diretamente temas deWindows . Porque a aparência de WPF é definido por modelos, WPF inclui um modelo para cada um do conhecido Windows temas, incluindo o Aero (Windows Vista) clássico, (Microsoft Windows 2000), Luna (Microsoft Windows XP) e Royale (Microsoft Windows XP Media Center Edition 2005). Esses temas são empacotados como dicionários de recurso que serão resolvidos se os recursos não são encontrados em um aplicativo. Muitos aplicativos dependem desses temas para definir sua aparência visual; restante consistente com Windows aparência ajuda os usuários a se familiarizar-se com mais aplicativos com mais facilidade.
On the other hand, the user experience for some applications does not necessarily come from the standard themes. Por exemplo, Microsoft Windows Media Player opera em dados de áudio e vídeo e se beneficia com um estilo diferente da experiência do usuário. Such UIs tend to provide customized, application-specific themes. Eles são conhecidos como capas e os aplicativos que são os geralmente fornecem ganchos pelo qual os usuários podem personalizar vários aspectos da capa. Microsoft Windows Media Player tem várias prefabricated capas, bem como um host de terceiros capas.
Both themes and skins in WPF are most easily defined using resource dictionaries. The following example shows sample skin definitions.
<!-- Blue Skin -->
<ResourceDictionary
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SDKSample">
<Style TargetType="{x:Type Button}">
<Setter Property="Background" Value="Blue" />
</Style>
...
</ResourceDictionary>
<!-- Yellow Skin -->
<ResourceDictionary
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SDKSample">
<Style TargetType="{x:Type Button}">
<Setter Property="Background" Value="Yellow" />
</Style>
...
</ResourceDictionary>
For more information, see "Shared Resources and Themes" in Styling and Templating.
Custom Controls
Embora WPF fornece um host de suporte de personalização, você pode encontrar situações onde existentes WPF controles não atender às necessidades do seu aplicativo ou usuários. This can occur when:
The UI that you require cannot be created by customizing the look and feel of existing WPF implementations.
The behavior that you require is not supported (or not easily supported) by existing WPF implementations.
At this point, however, you can take advantage of one of three WPF models to create a new control. Each model targets a specific scenario and requires your custom control to derive from a particular WPF base class. The three models are listed here:
User Control Model. A custom control derives from UserControl and is composed of one or more other controls.
Control Model. A custom control derives from Control and is used to build implementations that separate their behavior from their appearance using templates, much like the majority of WPF controls. Deriving from Control allows you more freedom for creating a custom UI than user controls, but it may require more effort.
Framework Element Model. A custom control derives from FrameworkElement when its appearance is defined by custom rendering logic (not templates).
The following example shows a custom numeric up/down control that derives from UserControl.
<UserControl
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.NumericUpDown">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<!-- Value text box -->
<Border BorderThickness="1" BorderBrush="Gray" Margin="2" Grid.RowSpan="2"
VerticalAlignment="Center" HorizontalAlignment="Stretch">
<TextBlock Name="valueText" Width="60" TextAlignment="Right" Padding="5"/>
</Border>
<!-- Up/Down buttons -->
<RepeatButton Name="upButton" Click="upButton_Click" Grid.Column="1"
Grid.Row="0">Up</RepeatButton>
<RepeatButton Name="downButton" Click="downButton_Click" Grid.Column="1"
Grid.Row="1">Down</RepeatButton>
</Grid>
</UserControl>
imports System 'EventArgs
imports System.Windows 'DependencyObject, DependencyPropertyChangedEventArgs,
' FrameworkPropertyMetadata, PropertyChangedCallback,
' RoutedPropertyChangedEventArgs
imports System.Windows.Controls 'UserControl
Namespace SDKSample
' Interaction logic for NumericUpDown.xaml
Partial Public Class NumericUpDown
Inherits System.Windows.Controls.UserControl
'NumericUpDown user control implementation
...
End Class
End Namespace
using System; // EventArgs
using System.Windows; // DependencyObject, DependencyPropertyChangedEventArgs,
// FrameworkPropertyMetadata, PropertyChangedCallback,
// RoutedPropertyChangedEventArgs
using System.Windows.Controls; // UserControl
namespace SDKSample
{
public partial class NumericUpDown : UserControl
{
// NumericUpDown user control implementation
...
}
}
The next example illustrates the XAML that is required to incorporate the user control into a Window.
<Window
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.UserControlWindow"
xmlns:local="clr-namespace:SDKSample"
Title="User Control Window">
...
<!-- Numeric Up/Down user control -->
<local:NumericUpDown />
...
</Window>
The following figure shows the NumericUpDown control hosted in a Window.
For more information on custom controls, see Visão geral sobre criação de controles.
WPF Best Practices
As with any development platform, WPF can be used in a variety of ways to achieve the desired result. As a way of ensuring that your WPF applications provide the required user experience and meet the demands of the audience in general, there are recommended best practices for accessibility, globalization and localization, and performance. See the following for more information:
Summary
WPF is a comprehensive presentation technology for building a wide variety of visually stunning client applications. This introduction has provided a look at the key features of WPF.
The next step is to build WPF applications!
As you build them, you can come back to this introduction for a refresher on the key features and to find references to more detailed coverage of the features covered in this introduction.
Recommended Overviews and Samples
The following overviews and samples are mentioned in this introduction.
Overviews
Práticas recomendadas de Acessibilidade Visão Geral do Gerenciamento de Aplicativo Revisão de Associação de Dados |
Visão geral sobre eventos roteados |
Samples
Galeria de exemplo de animação |
Introdução ao exemplo de modelagem de dados Introdução ao exemplo de modelagem e os estilos |