Search code examples
c#.netwpfwindow

How to detect the first show of a WPF Window?


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


Solution

  • 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;
    }