How to detect the first show of a WPF Window?
Solution 1
There is an event called Loaded
that you can use to determine when your window is ready.
From MSDN
Occurs when the element is laid out, rendered, and ready for interaction.
set the handler in XAML
<StackPanel
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.FELoaded"
Loaded="OnLoad"
Name="root">
</StackPanel>
add the code-behind
void OnLoad(object sender, RoutedEventArgs e)
{
Button b1 = new Button();
b1.Content = "New Button";
root.Children.Add(b1);
b1.Height = 25;
b1.Width = 200;
b1.HorizontalAlignment = HorizontalAlignment.Left;
}
Solution 2
Loaded can be called more than once.
The Loaded event and the Initialized event
According to my test and the link above, Loaded event can be fired more than once.
So, you need to set a flag in the OnLoaded handler.
For example, if Stack Panel is inside TabItem control, loaded will be called every time you step into tab.
Daniel Peñalba
Software Engineer at Unity Technologies, Valladolid, Spain. Currently developing gmaster, Plastic SCM and SemanticMerge. Areas: C# GUI development Winforms and WPF expert ASP .NET Core Multiplatform UI development with Mono (Linux and OSX, GTK# and MonoMac) Eclipse plugin, Java Automated testing, NUnit, Moq, PNUnit and TestComplete Email: dpenalba[AT]codicesoftware[DOT]com I play the guitar at Sharon Bates, the greatest Spanish rock band.
Updated on July 07, 2022Comments
-
Daniel Peñalba almost 2 years
I was wondering which is the correct way to detect when a WPF windows has been shown for the first time?
-
Brandon Dybala about 11 yearsAccording to this MSDN blog, the
Loaded
event actually occurs just before the first render. -
Jesse Chisholm about 9 yearsAnd the OP wanted the WPF equivalent of
Form.Shown
, not the equivalent ofForm.Loaded
. WPF does not make this a trivial translation. This thread (stackoverflow.com/questions/9191256/window-shown-event-in-wpf) suggests overridingOnContentRendered
with your own flag for tracking whether it is the first time or not. -
Jesse Chisholm about 9 yearsThis will never get to the
else
clause asOnLoad
is only ever called once. Before the first time the window isShown
. The OP's problem is that WPF does not have aWindow.OnShown
trivial equivalent. -
Bugs over 6 yearsA link to a solution is welcome, but please ensure your answer is useful without it: add context around the link so your fellow users will have some idea what it is and why it’s there, then quote the most relevant part of the page you're linking to in case the target page is unavailable. Answers that are little more than a link may be deleted.