Steps Of Control Creation Process WPF

2019-02-20 11:43发布

问题:

I have been searching for such an explaination for a while and I couldn't have found any yet. The thing is that I would like to know the steps of initialization/creation process of a Wpf Control.

Lets take a simple Button and I would like to know what is happening when constructor gets called, when is the control added to visualTree/logicalTree, when does invocation of dependencyproperty values happen, when is ApplyTemplate() called?

I need this information to be able to write proper custom control and I think it will help others too in case they wonder why this.Template.FindName("test") always returns "null" when being called inside a constructor of a control.

Can anyone answer this or provide me with links of tutorials where the concept of initizaling a control is poperly explained?

Thanks :)

回答1:

Per this SO answer here

Sequence of events when a Window is created and shown

As requested, here is the sequence of major events in WPF when a window is created and shown:

  1. Constructors and getters/setters are called as objects are created, including PropertyChangedCallback, ValidationCallback, etc on the objects being updated and any objects that inherit from them

  2. As each element gets added to a visual or logical tree its Intialized event is fired, which causes Styles and Triggers to be found applied in addition to any element-specific initialization you may define [note: Initialized event not fired for leaves in a logical tree if there is no PresentationSource (eg Window) at its root]

  3. The window and all non-collapsed Visuals on it are Measured, which causes an ApplyTemplate at each Control, which causes additional object tree construction including more constructors and getters/setters

  4. The window and all non-collapsed Visuals on it are Arranged

  5. The window and its descendants (both logical and visual) receive a Loaded event

  6. Any data bindings that failed when they were first set are retried

  7. The window and its descendants are given an opportunity to render their content visually

Steps 1-2 are done when the Window is created, whether or not it is shown. The other steps generally don't happen until a Window is shown, but they can happen earlier if triggered manually.

Also, I personally found the DispatcherPriority Enum useful in determining the event order in some cases

  • Invalid
  • Inactive
  • SystemIdle
  • ApplicationIdle
  • ContextIdle
  • Background
  • Input
  • Loaded
  • Render
  • DataBind
  • Normal - Constructors run here
  • Send