Reputation: 31857
I was wondering which is the correct way to detect when a WPF windows has been shown for the first time?
Upvotes: 8
Views: 12905
Reputation: 45
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.
Upvotes: 3
Reputation: 13207
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;
}
Upvotes: 9
Reputation: 639
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
}
}
Upvotes: -1