I was wondering which is the correct way to detect when a WPF windows has been shown for the first time?
Asked
Active
Viewed 1.2k times
8
-
WinForms has a Shown event, but i think it is not available in WPF. Maye [Initialized](http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.initialized.aspx) is the correct way to use – Jehof Apr 19 '13 at 13:57
3 Answers
9
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;
}

bash.d
- 13,029
- 3
- 29
- 42
-
1According to [this MSDN blog](http://blogs.msdn.com/b/mikehillberg/archive/2006/09/19/loadedvsinitialized.aspx), the `Loaded` event actually occurs just before the first render. – Brandon Dybala Apr 19 '13 at 17:57
-
3And the OP wanted the WPF equivalent of `Form.Shown`, not the equivalent of `Form.Loaded`. WPF does not make this a trivial translation. This thread (http://stackoverflow.com/questions/9191256/window-shown-event-in-wpf) suggests overriding `OnContentRendered` with your own flag for tracking whether it is the first time or not. – Jesse Chisholm Feb 16 '15 at 00:25
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.

Jeong Minu
- 35
- 1
- 7
-
1A link to a solution is welcome, but please ensure your answer is useful without it: [add context around the link](//meta.stackexchange.com/a/8259) 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.](//stackoverflow.com/help/deleted-answers) – Bugs Aug 29 '17 at 08:13
-1
i would suggest to make a bool flag and check it, and in the constructor set it to true
bool FirstTime = true;
void OnLoad(object sender, RoutedEventArgs e)
{
if (FirstTime)
{
FirstTime = false;
//do your stuff first-time
}
else
{
//do your stuff for other
}
}

Postback
- 619
- 2
- 9
- 27
-
2This will never get to the `else` clause as `OnLoad` is only ever called once. Before the first time the window is `Shown`. The OP's problem is that WPF does not have a `Window.OnShown` trivial equivalent. – Jesse Chisholm Feb 16 '15 at 00:26