Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect the first show of a WPF Window?

Tags:

c#

.net

window

wpf

I was wondering which is the correct way to detect when a WPF windows has been shown for the first time?

like image 537
Daniel Peñalba Avatar asked Apr 19 '13 13:04

Daniel Peñalba


1 Answers

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;
}
like image 191
bash.d Avatar answered Sep 18 '22 18:09

bash.d