Compartilhar via


Visão geral do WPF do Windows

Users interact with Windows Presentation Foundation (WPF) standalone applications through windows. O objetivo principal de uma janela é hospedar conteúdo que visualiza dados e permite que os usuários interajam com dados. Autônomo WPF aplicativos fornecem suas próprias janelas usando o Window classe. Este tópico apresenta Window antes de abordar os conceitos básicos da criação e gerenciamento do windows em todos os aplicativos autônomos.

Observação

Browser-hosted WPF applications, including XAML browser applications (XBAPs) and loose Extensible Application Markup Language (XAML) pages, don't provide their own windows.Instead, they are hosted in windows provided by Windows Internet Explorer.See Visão geral sobre WPF XAML Browser Applications.

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

  • The Window Class
  • Implementing a Window
  • Configuring a Window Definition for MSBuild
  • Window Lifetime
  • Window Location
  • Window Size
  • Order of Precedence for Sizing Properties
  • Window State
  • Window Appearance
  • Security Considerations
  • Other Types of Windows
  • Tópicos relacionados

The Window Class

The following figure illustrates the constituent parts of a window.

Elementos de janela

Uma janela está dividida em duas áreas: a área não-cliente e a área do cliente.

The non-client area of a window is implemented by WPF and includes the parts of a window that are common to most windows, including the following:

  • A border.

  • A title bar.

  • An icon.

  • Minimize, Maximize, and Restore buttons.

  • A Close button.

  • Um menu de sistema com os itens de menu que permitem aos usuários minimizar, maximizar, restaurar, mover, redimensionar e fechar uma janela.

The client area of a window is the area within a window's non-client area and is used by developers to add application-specific content, such as menu bars, tool bars, and controls.

In WPF, a window is encapsulated by the Window class that you use to do the following:

  • Display a window.

  • Configure the size, position, and appearance of a window.

  • Host application-specific content.

  • Manage the lifetime of a window.

Implementing a Window

The implementation of a typical window comprises both appearance and behavior, where appearance defines how a window looks to users and behavior defines the way a window functions as users interact with it. Em WPF, você pode implementar a aparência e comportamento de uma janela usando o código ou XAML marcação.

Em geral, no entanto, a aparência de uma janela é implementada usando XAML a marcação e seu comportamento é implementado usando o code-behind, conforme mostrado no exemplo a seguir.

<Window 
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="SDKSample.MarkupAndCodeBehindWindow">

  <!-- Client area (for content) -->

</Window>

Imports System.Windows ' Window

Namespace SDKSample
    Partial Public Class MarkupAndCodeBehindWindow
        Inherits Window
        Public Sub New()
            InitializeComponent()
        End Sub
    End Class
End Namespace
using System.Windows; // Window

namespace SDKSample
{
    public partial class MarkupAndCodeBehindWindow : Window
    {
        public MarkupAndCodeBehindWindow()
        {
            InitializeComponent();
        }
    }
}

Para habilitar um XAML o arquivo de marcação e o arquivo code-behind para trabalharem juntos, a seguir é necessária:

  • In markup, the Window element must include the x:Class attribute. When the application is built, the existence of x:Class in the markup file causes Microsoft build engine (MSBuild) to create a partial class that derives from Window and has the name that is specified by the x:Class attribute. This requires the addition of an XML namespace declaration for the XAML schema (xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"). Gerado partial classe implementa o InitializeComponent método, que é chamado para registrar os eventos e definir as propriedades que são implementadas na marcação.

  • In code-behind, the class must be a partial class with the same name that is specified by the x:Class attribute in markup, and it must derive from Window. This allows the code-behind file to be associated with the partial class that is generated for the markup file when the application is built (see Building a WPF Application (WPF)).

  • No code-behind, o Window classe deve implementar um construtor que chama o InitializeComponent método. InitializeComponenté implementada pela marcação da gerado o arquivo partial classe para registrar eventos e definir propriedades que são definidas na marcação.

Observação

When you add a new Window to your project by using Microsoft Visual Studio, the Window is implemented using both markup and code-behind, and includes the necessary configuration to create the association between the markup and code-behind files as described here.

With this configuration in place, you can focus on defining the appearance of the window in XAML markup and implementing its behavior in code-behind. O exemplo a seguir mostra uma janela com um botão, implementado em XAML a marcação e um manipulador de eventos para o botão Click evento, implementado em código-behind.

<Window 
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="SDKSample.MarkupAndCodeBehindWindow">
  <!-- Client area (for content) -->
  <Button Click="button_Click">Click This Button</Button>
</Window>

Imports System.Windows

Namespace SDKSample
    Partial Public Class MarkupAndCodeBehindWindow
        Inherits Window
        Public Sub New()
            InitializeComponent()
        End Sub

        Private Sub button_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
            MessageBox.Show("Button was clicked.")
        End Sub
    End Class
End Namespace
using System.Windows;

namespace SDKSample
{
    public partial class MarkupAndCodeBehindWindow : Window
    {
        public MarkupAndCodeBehindWindow()
        {
            InitializeComponent();
        }

        void button_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Button was clicked.");
        }
    }
}

Configuring a Window Definition for MSBuild

How you implement your window determines how it is configured for MSBuild. Para uma janela que é definida usando ambos XAML marcação e code-behind:

  • XAMLarquivos de marcação são configurados como MSBuild Page itens.

  • Arquivos code-behind são configurados como MSBuild Compile itens.

This is shown in the following MSBuild project file.

<Project ... xmlns="https://schemas.microsoft.com/developer/msbuild/2003">
    ...
    <Page Include="MarkupAndCodeBehindWindow.xaml" />
    <Compile Include=" MarkupAndCodeBehindWindow.xaml.cs" />
    ...
</Project>

For information about building WPF applications, see Building a WPF Application (WPF).

Window Lifetime

As with any class, a window has a lifetime that begins when it is first instantiated, after which it is opened, activated and deactivated, and eventually closed.

Esta seção contém as seguintes subseções.

  • Opening a Window
  • Window Activation
  • Closing a Window
  • Window Lifetime Events

Opening a Window

To open a window, you first create an instance of it, which is demonstrated in the following example.

<Application
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="SDKSample.App"
    Startup="app_Startup">
</Application>

Imports System.Windows

Namespace SDKSample
    Partial Public Class App
        Inherits Application
        Private Sub app_Startup(ByVal sender As Object, ByVal e As StartupEventArgs)
            ' Create a window
            Dim window As New MarkupAndCodeBehindWindow()

            ' Open a window
            window.Show()
        End Sub
    End Class
End Namespace
using System.Windows;
namespace SDKSample
{
    public partial class App : Application
    {
        void app_Startup(object sender, StartupEventArgs e)
        {
            // Create a window
            MarkupAndCodeBehindWindow window = new MarkupAndCodeBehindWindow();

            // Open a window
            window.Show();
        }
    }
}

In this example, the MarkupAndCodeBehindWindow is instantiated when the application starts, which occurs when the Startup event is raised.

When a window is instantiated, a reference to it is automatically added to a list of windows that is managed by the Application object (see Application.Windows). Additionally, the first window to be instantiated is, by default, set by Application as the main application window (see Application.MainWindow).

The window is finally opened by calling the Show method; the result is shown in the following figure.

Uma janela aberta chamando Window.Show

A window that is opened by calling Show is a modeless window, which means that the application operates in a mode that allows users to activate other windows in the same application.

Observação

ShowDialog is called to open windows such as dialog boxes modally.See Dialog Boxes Overview for more information.

When Show is called, a window performs initialization work before it is shown to establish infrastructure that allows it to receive user input. When the window is initialized, the SourceInitialized event is raised and the window is shown.

As a shortcut, StartupUri can be set to specify the first window that is opened automatically when an application starts.

<Application
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="SDKSample.App"
    StartupUri="PlainWindow.xaml" />

When the application starts, the window specified by the value of StartupUri is opened modelessly; internally, the window is opened by calling its Show method.

Window Ownership

A window that is opened by using the Show method does not have an implicit relationship with the window that created it; users can interact with either window independently of the other, which means that either window can do the following:

  • Cover the other (unless one of the windows has its Topmost property set to true).

  • Be minimized, maximized, and restored without affecting the other.

Some windows require a relationship with the window that opens them. Por exemplo, um Integrated Development Environment (IDE) aplicativo talvez propriedade janelas abertas e as janelas de ferramentas cujo comportamento típico é cobrir a janela em que os criou. Furthermore, such windows should always close, minimize, maximize, and restore in concert with the window that created them. Such a relationship can be established by making one window own another, and is achieved by setting the Owner property of the owned window with a reference to the owner window. This is shown in the following example.

' Create a window and make this window its owner
Dim ownedWindow As New Window()
ownedWindow.Owner = Me
ownedWindow.Show()
// Create a window and make this window its owner
Window ownedWindow = new Window();
ownedWindow.Owner = this;
ownedWindow.Show();

After ownership is established:

  • The owned window can reference its owner window by inspecting the value of its Owner property.

  • The owner window can discover all the windows it owns by inspecting the value of its OwnedWindows property.

Impedindo a ativação de janela

Existem cenários onde windows devem ser ativados não quando mostrado, como janelas de conversa de um aplicativo do estilo do messenger de Internet ou o windows de notificação de um aplicativo de email.

Se seu aplicativo tiver uma janela que não deve ser ativada quando mostrado, você pode definir sua ShowActivated propriedade para false antes de chamar o Show método para a primeira vez. Como conseqüência:

  • A janela não está ativada.

  • A janela Activated evento não é aumentado.

  • Janela ativada no momento permanece ativada.

A janela será tornam-se ativada, no entanto, assim que o usuário o ativa clicando-se o cliente ou a área não-cliente. Nesse caso:

  • A janela é ativada.

  • A janela Activated evento é gerado.

  • A janela ativada anteriormente é desativada.

  • A janela Deactivated e Activated são subseqüentemente gerados conforme o esperado em resposta a ações do usuário.

Window Activation

Quando uma janela é aberta pela primeira vez, torna-se a janela ativa (a menos que ele é mostrado com ShowActivated definido como false). The active window is the window that is currently capturing user input, such as key strokes and mouse clicks. When a window becomes active, it raises the Activated event.

Observação

When a window is first opened, the Loaded and ContentRendered events are raised only after the Activated event is raised.With this in mind, a window can effectively be considered opened when ContentRendered is raised.

After a window becomes active, a user can activate another window in the same application, or activate another application. When that happens, the currently active window becomes deactivated and raises the Deactivated event. Likewise, when the user selects a currently deactivated window, the window becomes active again and Activated is raised.

One common reason to handle Activated and Deactivated is to enable and disable functionality that can only run when a window is active. For example, some windows display interactive content that requires constant user input or attention, including games and video players. The following example is a simplified video player that demonstrates how to handle Activated and Deactivated to implement this behavior.

<Window
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="SDKSample.CustomMediaPlayerWindow"
    Activated="window_Activated"
    Deactivated="window_Deactivated">

    <!-- Media Player -->
    <MediaElement 
      Name="mediaElement" 
      Stretch="Fill" 
      LoadedBehavior="Manual" 
      Source="numbers.wmv" />

</Window>

Imports System ' EventArgs
Imports System.Windows ' Window

Namespace SDKSample
    Partial Public Class CustomMediaPlayerWindow
        Inherits Window
        Public Sub New()
            InitializeComponent()
        End Sub

        Private Sub window_Activated(ByVal sender As Object, ByVal e As EventArgs)
            ' Recommence playing media if window is activated
            Me.mediaElement.Play()
        End Sub

        Private Sub window_Deactivated(ByVal sender As Object, ByVal e As EventArgs)
            ' Pause playing if media is being played and window is deactivated
            Me.mediaElement.Pause()
        End Sub
    End Class
End Namespace
using System; // EventArgs
using System.Windows; // Window

namespace SDKSample
{
    public partial class CustomMediaPlayerWindow : Window
    {
        public CustomMediaPlayerWindow()
        {
            InitializeComponent();
        }

        void window_Activated(object sender, EventArgs e)
        {
            // Recommence playing media if window is activated
            this.mediaElement.Play();
        }

        void window_Deactivated(object sender, EventArgs e)
        {
            // Pause playing if media is being played and window is deactivated
            this.mediaElement.Pause();
        }
    }
}

Other types of applications may still run code in the background when a window is deactivated. For example, a mail client may continue polling the mail server while the user is using other applications. Applications like these often provide different or additional behavior while the main window is deactivated. With respect to the mail program, this may mean both adding the new mail item to the inbox and adding a notification icon to the system tray. A notification icon need only be displayed when the mail window isn't active, which can be determined by inspecting the IsActive property.

If a background task completes, a window may want to notify the user more urgently by calling Activate method. If the user is interacting with another application activated when Activate is called, the window's taskbar button flashes. If a user is interacting with the current application, calling Activate will bring the window to the foreground.

Observação

You can handle application-scope activation using the Application.Activated and Application.Deactivated events.

Closing a Window

The life of a window starts coming to an end when a user closes it. A window can be closed by using elements in the non-client area, including the following:

  • The Close item of the System menu.

  • Pressing ALT+F4.

  • Pressing the Close button.

You can provide additional mechanisms to the client area to close a window, the more common of which include the following:

  • An Exit item in the File menu, typically for main application windows.

  • A Close item in the File menu, typically on a secondary application window.

  • A Cancel button, typically on a modal dialog box.

  • A Close button, typically on a modeless dialog box.

To close a window in response to one of these custom mechanisms, you need to call the Close method. The following example implements the ability to close a window by choosing the Exit on the File menu.

<Window 
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="SDKSample.WindowWithFileExit">

  <Menu>
    <MenuItem Header="_File">
      <MenuItem Header="E_xit" Click="fileExitMenuItem_Click" />
    </MenuItem>
  </Menu>

</Window>

Imports System.Windows ' window, RoutedEventArgs

Namespace SDKSample
    Partial Public Class WindowWithFileExit
        Inherits System.Windows.Window
        Public Sub New()
            InitializeComponent()
        End Sub

        Private Sub fileExitMenuItem_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
            ' Close this window
            Me.Close()
        End Sub
    End Class
End Namespace
using System.Windows; // window, RoutedEventArgs

namespace SDKSample
{
    public partial class WindowWithFileExit : System.Windows.Window
    {
        public WindowWithFileExit()
        {
            InitializeComponent();
        }

        void fileExitMenuItem_Click(object sender, RoutedEventArgs e)
        {
            // Close this window
            this.Close();
        }
    }
}

Quando uma janela é fechada, ele lança dois eventos: Closing and Closed.

Closing is raised before the window closes, and it provides a mechanism by which window closure can be prevented. One common reason to prevent window closure is if window content contains modified data. In this situation, the Closing event can be handled to determine whether data is dirty and, if so, to ask the user whether to either continue closing the window without saving the data or to cancel window closure. The following example shows the key aspects of handling Closing.


Imports System ' EventArgs
Imports System.ComponentModel ' CancelEventArgs
Imports System.Windows ' window

Namespace VisualBasic
    Partial Public Class DataWindow
        Inherits Window
        ' Is data dirty
        Private isDataDirty As Boolean = False


...


        Private Sub DataWindow_Closing(ByVal sender As Object, ByVal e As CancelEventArgs)
            MessageBox.Show("Closing called")

            ' If data is dirty, notify user and ask for a response
            If Me.isDataDirty Then
                Dim msg As String = "Data is dirty. Close without saving?"
                Dim result As MessageBoxResult = MessageBox.Show(msg, "Data App", MessageBoxButton.YesNo, MessageBoxImage.Warning)
                If result = MessageBoxResult.No Then
                    ' If user doesn't want to close, cancel closure
                    e.Cancel = True
                End If
            End If
        End Sub
    End Class
End Namespace
using System; // EventArgs
using System.ComponentModel; // CancelEventArgs
using System.Windows; // window

namespace CSharp
{
    public partial class DataWindow : Window
    {
        // Is data dirty
        bool isDataDirty = false;


...


        void DataWindow_Closing(object sender, CancelEventArgs e)
        {
            MessageBox.Show("Closing called");

            // If data is dirty, notify user and ask for a response
            if (this.isDataDirty)
            {
                string msg = "Data is dirty. Close without saving?";
                MessageBoxResult result = 
                  MessageBox.Show(
                    msg, 
                    "Data App", 
                    MessageBoxButton.YesNo, 
                    MessageBoxImage.Warning);
                if (result == MessageBoxResult.No)
                {
                    // If user doesn't want to close, cancel closure
                    e.Cancel = true;
                }
            }
        }
    }
}

The Closing event handler is passed a CancelEventArgs, which implements the Boolean Cancel property that you set to true to prevent a window from closing.

If Closing is not handled, or it is handled but not canceled, the window will close. Just before a window actually closes, Closed is raised. At this point, a window cannot be prevented from closing.

Observação

An application can be configured to shut down automatically when either the main application window closes (see MainWindow) or the last window closes.For details, see ShutdownMode.

While a window can be explicitly closed through mechanisms provided in the non-client and client areas, a window can also be implicitly closed as a result of behavior in other parts of the application or Windows, including the following:

Observação

A window cannot be reopened after it is closed.

Window Lifetime Events

The following illustration shows the sequence of the principal events in the lifetime of a window.

Tempo de vida de janela

A ilustração a seguir mostra a seqüência dos eventos principais na vida útil de uma janela que é mostrada sem ativação (ShowActivated for definido como false antes da janela é mostrada).

Tempo de vida de janela (Window.ShowActivated = False)

Window Location

While a window is open, it has a location in the x and y dimensions relative to the desktop. This location can be determined by inspecting the Left and Top properties, respectively. You can set these properties to change the location of the window.

You can also specify the initial location of a Window when it first appears by setting the WindowStartupLocation property with one of the following WindowStartupLocation enumeration values:

If the startup location is specified as Manual, and the Left and Top properties have not been set, Window will ask Windows for a location to appear in.

Topmost Windows and Z-Order

Besides having an x and y location, a window also has a location in the z dimension, which determines its vertical position with respect to other windows. Isso é conhecido como a ordem z da janela, e há dois tipos: ordem-z normal e superior da ordem-z. The location of a window in the normal z-order is determined by whether it is currently active or not. By default, a window is located in the normal z-order. The location of a window in the topmost z-order is also determined by whether it is currently active or not. Furthermore, windows in the topmost z-order are always located above windows in the normal z-order. A window is located in the topmost z-order by setting its Topmost property to true.

<Window 
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    Topmost="True">


...


</Window>

Within each z-order, the currently active window appears above all other windows in the same z-order.

Window Size

Besides having a desktop location, a window has a size that is determined by several properties, including the various width and height properties and SizeToContent.

MinWidth, Width, and MaxWidth are used to manage the range of widths that a window can have during its lifetime, and are configured as shown in the following example.

<Window 
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    MinWidth="300" Width="400" MaxWidth="500">


...


</Window>

Window height is managed by MinHeight, Height, and MaxHeight, and are configured as shown in the following example.

<Window 
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    MinHeight="300" Height="400" MaxHeight="500">


...


</Window>

Because the various width values and height values each specify a range, it is possible for the width and height of a resizable window to be anywhere within the specified range for the respective dimension. To detect its current width and height, inspect ActualWidth and ActualHeight, respectively.

If you'd like the width and height of your window to have a size that fits to the size of the window's content, you can use the SizeToContent property, which has the following values:

  • Manual. Não foi possível encontrar nenhum efeito (padrão).

  • Width. Ajustar à largura de conteúdo, que tem o mesmo efeito que definir ambos MinWidth e MaxWidth a largura do conteúdo.

  • Height. Ajustar à altura de conteúdo, que tem o mesmo efeito que definir ambos MinHeight e MaxHeight para a altura do conteúdo.

  • WidthAndHeight. Ajustar ao conteúdo largura e altura, que tem o mesmo efeito que definir ambos MinHeight e MaxHeight para a altura do conteúdo e a configuração de ambos os MinWidth e MaxWidth a largura do conteúdo.

The following code shows a window that automatically sizes to fit its content, both vertically and horizontally, when first shown.

<Window 
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    SizeToContent="WidthAndHeight">


...


</Window>

Order of Precedence for Sizing Properties

Essentially, the various sizes properties of a window combine to define the range of width and height for a resizable window. To ensure a valid range is maintained, Window evaluates the values of the size properties using the following orders of precedence.

For Height Properties:

  1. FrameworkElement.MinHeight >

  2. FrameworkElement.MaxHeight >

  3. SizeToContent.Height/SizeToContent.WidthAndHeight >

  4. FrameworkElement.Height

For Width Properties:

  1. FrameworkElement.MinWidth >

  2. FrameworkElement.MaxWidth >

  3. SizeToContent.Width/SizeToContent.WidthAndHeight >

  4. FrameworkElement.Width

The order of precedence can also determine the size of a window when it is maximized, which is managed with the WindowState property.

Window State

Durante o ciclo de vida de uma janela redimensionável, ele pode ter três estados: normal, minimizada e maximizado. A window with a normal state is the default state of a window. A window with this state allows a user to move and resize it by using a resize grip or the border, if it is resizable.

A window with a minimized state collapses to its task bar button if ShowInTaskbar is set to true; otherwise, it collapses to the smallest possible size it can be and relocates itself to the bottom-left corner of the desktop. Neither type of minimized window can be resized using a border or resize grip, although a minimized window that isn't shown in the task bar can be dragged around the desktop.

A window with a maximized state expands to the maximum size it can be, which will only be as large as its MaxWidth, MaxHeight, and SizeToContent properties dictate. Like a minimized window, a maximized window cannot be resized by using a resize grip or by dragging the border.

Observação

Os valores de Top, Left, Width, e Height Propriedades de uma janela sempre representam os valores para o estado normal, mesmo quando a janela está maximizada ou minimizada atualmente.

The state of a window can be configured by setting its WindowState property, which can have one of the following WindowState enumeration values:

The following example shows how to create a window that is shown as maximized when it opens.

<Window 
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    WindowState="Maximized">


...


</Window>

In general, you should set WindowState to configure the initial state of a window. Once a resizable window is shown, users can press the minimize, maximize, and restore buttons on the window's title bar to change the window state.

Window Appearance

You change the appearance of the client area of a window by adding window-specific content to it, such as buttons, labels, and text boxes. To configure the non-client area, Window provides several properties, which include Icon to set a window's icon and Title to set its title.

You can also change the appearance and behavior of non-client area border by configuring a window's resize mode, window style, and whether it appears as a button in the desktop task bar.

Esta seção contém as seguintes subseções.

  • Resize Mode
  • Window Style
  • Task Bar Presence

Resize Mode

Depending on the WindowStyle property, you can control how (and if) users can resize the window. The choice of window style affects whether a user can resize the window by dragging its border with the mouse, whether the Minimize, Maximize, and Resize buttons appear on the non-client area, and, if they do appear, whether they are enabled.

You can configure how a window resizes by setting its ResizeMode property, which can be one of the following ResizeMode enumeration values:

Como com WindowStyle, o modo de redimensionamento de uma janela é improvável que sejam alteradas durante seu ciclo de vida, o que significa que você irá provavelmente defini-la de XAML marcação.

<Window 
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    ResizeMode="CanResizeWithGrip">


...


</Window>

Note that you can detect whether a window is maximized, minimized, or restored by inspecting the WindowState property.

Window Style

The border that is exposed from the non-client area of a window is suitable for most applications. However, there are circumstances where different types of borders are needed, or no borders are needed at all, depending on the type of window.

To control what type of border a window gets, you set its WindowStyle property with one of the following values of the WindowStyle enumeration:

The effect of these window styles are illustrated in the following figure.

Estilos de janela

Você pode definir WindowStyle usando um XAML marcação ou código; porque é improvável que sejam alteradas durante a vida útil de uma janela, você irá provavelmente configurar usando XAML marcação.

<Window 
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    WindowStyle="ToolWindow">


...


</Window>

Non-Rectangular Window Style

There are also situations where the border styles that WindowStyle allows you to have are not sufficient. For example, you may want to create an application with a non-rectangular border, like Microsoft Windows Media Player uses.

For example, consider the speech bubble window shown in the following figure.

Janela Nonrectangular

This type of window can be created by setting the WindowStyle property to None, and by using special support that Window has for transparency.

<Window 
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    WindowStyle="None"
    AllowsTransparency="True"
    Background="Transparent">


...


</Window>

This combination of values instructs the window to render completely transparent. In this state, the window's non-client area adornments (the Close menu, Minimize, Maximize, and Restore buttons, and so on) cannot be used. Consequently, you need to provide your own.

Task Bar Presence

The default appearance of a window includes a task bar button, like the one shown in the following figure.

Janela com um botão da barra de tarefas

Some types of windows don't have a task bar button, such as message boxes and dialog boxes (see Dialog Boxes Overview). You can control whether the task bar button for a window is shown by setting the ShowInTaskbar property (true by default).

<Window 
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    ShowInTaskbar="False">


...


</Window>

Security Considerations

Window requires UnmanagedCode security permission to be instantiated. For applications installed on and launched from the local machine, this falls within the set of permissions that are granted to the application.

No entanto, isso fica fora do conjunto de permissões concedidas aos aplicativos que são iniciados a partir da Internet ou o Local da intranet zona usando ClickOnce. Consequently, users will receive a ClickOnce security warning and will need to elevate the permission set for the application to full trust.

Additionally, XBAPs cannot show windows or dialog boxes by default. For a discussion on standalone application security considerations, see Estratégia de segurança do WPF - Segurança da Plataforma.

Other Types of Windows

NavigationWindow is a window that is designed to host navigable content. For more information, see Visão geral de navegação).

Dialog boxes are windows that are often used to gather information from a user to complete a function. For example, when a user wants to open a file, the Open File dialog box is usually displayed by an application to get the file name from the user. For more information, see Dialog Boxes Overview.

Consulte também

Referência

Window

MessageBox

NavigationWindow

Application

Conceitos

Dialog Boxes Overview

Building a WPF Application (WPF)