Compartilhar via


Object Lifetime Events

This topic describes the specific WPF events that signify stages in an object lifetime of creation, use, and destruction.

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

  • Prerequisites
  • Object Lifetime Events
  • Common Lifetime Events for Elements
  • Lifetime Events Application Model Elements
  • Tópicos relacionados

Prerequisites

This topic assumes that you understand dependency properties from the perspective of a consumer of existing dependency properties on Windows Presentation Foundation (WPF) classes, and have read the Visão geral sobre propriedades de dependência topic. In order to follow the examples in this topic, you should also understand Extensible Application Markup Language (XAML) (see Visão geral do XAML (WPF)) and know how to write WPF applications.

Object Lifetime Events

All objects in Microsoft .NET Framework managed code go through a similar set of stages of life, creation, use, and destruction. Muitos objetos também têm um estágio de finalização da vida ocorre como parte da fase de destruição. WPFobjetos, mais especificamente, o visual objetos que WPF identifica como elementos, também tem um conjunto de estágios comuns de vida do objeto. The WPF programming and application models expose these stages as a series of events. There are four main types of objects in WPF with respect to lifetime events; elements in general, window elements, navigation hosts, and application objects. Windows and navigation hosts are also within the larger grouping of visual objects (elements). This topic describes the lifetime events that are common to all elements and then introduces the more specific ones that apply to application definitions, windows or navigation hosts.

Common Lifetime Events for Elements

Qualquer WPF framework-nível elemento (os objetos derivados de um FrameworkElement ou FrameworkContentElement) tem três eventos comuns da vida útil: Initialized, Loaded, and Unloaded.

Initialized

Initialized is raised first, and roughly corresponds to the initialization of the object by the call to its constructor. Because the event happens in response to initialization, you are guaranteed that all properties of the object are set. (An exception is expression usages such as dynamic resources or binding; these will be unevaluated expressions.) As a consequence of the requirement that all properties are set, the sequence of Initialized being raised by nested elements that are defined in markup appears to occur in order of deepest elements in the element tree first, then parent elements toward the root. This order is because the parent-child relationships and containment are properties, and therefore the parent cannot report initialization until the child elements that fill the property are also completely initialized.

When you are writing handlers in response to the Initialized event, you must consider that there is no guarantee that all other elements in the element tree (either logical tree or visual tree) around where the handler is attached have been created, particularly parent elements. Member variables may be null, or data sources might not yet be populated by the underlying binding (even at the expression level).

Loaded

Loaded is raised next. O Loaded evento é gerado antes do processamento final, mas após o sistema de layout tiverem sido calculados todos os valores necessários para processamento. Loadedimplica que a árvore lógica de um elemento contido é concluída e se conecta a uma fonte de apresentação que fornece o HWND e a superfície de processamento. Standard data binding (binding to local sources, such as other properties or directly defined data sources) will have occurred prior to Loaded. Asynchronous data binding (external or dynamic sources) might have occurred, but by definition of its asynchronous nature cannot be guaranteed to have occurred.

The mechanism by which the Loaded event is raised is different than Initialized. The Initialized event is raised element by element, without a direct coordination by a completed element tree. By contrast, the Loaded event is raised as a coordinated effort throughout the entire element tree (specifically, the logical tree). When all elements in the tree are in a state where they are considered loaded, the Loaded event is first raised on the root element. The Loaded event is then raised successively on each child element.

Observação

Esse comportamento superficialmente pode ser semelhante a encapsulamento para um roteados eventos.However, no information is carried from event to event.Each element always has the opportunity to handle its Loaded event, and marking the event data as handled has no effect beyond that element.

Descarregado

Unloaded is raised last and is initiated by either the presentation source or the visual parent being removed. When Unloaded is raised and handled, the element that is the event source parent (as determined by Parent property) or any given element upwards in the logical or visual trees may have already been unset, meaning that data binding, resource references, and styles may not be set to their normal or last known run-time value.

Lifetime Events Application Model Elements

Criação de eventos de tempo de vida comuns para os elementos são os seguintes elementos de modelo de aplicativo: Application, Window, Page, NavigationWindow, and Frame. These extend the common lifetime events with additional events that are relevant to their specific purpose. These are discussed in detail in the following locations:

Consulte também

Conceitos

Precedência de valores de propriedade de dependência

Visão geral sobre eventos roteados