What's the difference between the Window.Loaded
and Window.ContentRendered
events in WPF? Is the ContentRendered
event called first?
The description of the Window.ContentRendered
event here just says
Occurs after a window's content has been rendered.
The description of the Window.Loaded
event here says
Occurs when the element is laid out, rendered, and ready for interaction.
I have a case where I want to set the window's MaxHeight
to the height of the working area of the screen that is displaying my window. Which event should I do it in?
Edit:
I think I found what I was looking for, but I'm even more confused now. The Loaded
event happens first and then the ContentRendered
event happens. In the book Programming WPF by Chris Sells & Ian Griffiths, it says that the Loaded
event is
Raised just before the window is shown
While the 'ContentRendered` event is
Raised when the window's content is visually rendered.
This contradicts what the MSDN documentation says about the Loaded
event:
Occurs when the element is laid out, rendered, and ready for interaction.
This is even more confusing now.
Best Answer
I think there is little difference between the two events. To understand this, I created a simple example to manipulation:
XAML
Code behind
In this case the message
Loaded
appears the first after the messageContentRendered
. This confirms the information in the documentation.In general, in WPF the
Loaded
event fires if the element:Since in WPF the
Window
is the same element, but it should be generally content that is arranged in a root panel (for example:Grid
). Therefore, to monitor the content of theWindow
and created anContentRendered
event. Remarks from MSDN:That is, if we create a
Window
:It will only works
Loaded
event.With regard to access to the elements in the
Window
, they work the same way. Let's create aLabel
in the mainGrid
ofWindow
. In both cases we have successfully received access toWidth
:As for the
Styles
andTemplates
, at this stage they are successfully applied, and in these events we will be able to access them.For example, we want to add a
Button
:In the case of
Loaded
event,Button
to add toGrid
immediately at the appearance of theWindow
. In the case ofContentRendered
event,Button
to add toGrid
after all its content will appear.Therefore, if you want to add items or changes before load
Window
you must use theLoaded
event. If you want to do the operations associated with the content ofWindow
such as taking screenshots you will need to use an eventContentRendered
.