WPF: OnLoad event

This entry is part 6 of 54 in the series Learn WPF

We know that in Windows, there is an on load event where our code will be initialized and run.

Here, I illustrate how a button is created when the windows event OnLoad is triggered.

The event OnLoad event is defined in line 4 in MainWindow.xaml.

MainWindow.xaml
<Window x:Class="On_Load.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Loaded="OnLoad"      
        Title="MainWindow" Height="350" Width="525">
    <StackPanel Name="stack">
        
    </StackPanel>
</Window>

MainWindow.xaml.cs
using System.Windows;
using System.Windows.Controls;

namespace On_Load
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        void OnLoad(object sender, RoutedEventArgs e)
        {
            Button b1 = new Button();
            b1.Content = "New Button";
            stack.Children.Add(b1);
            b1.Height = 25;
            b1.Width = 200;
            b1.HorizontalAlignment = HorizontalAlignment.Center;
        }
    }
}
We create a button using the Button object.  We give the Button instance name as b1.

We have also given an instance name stack to the StackPanel.  To add the Button object into the StackPanel, we simply use:

stack.Children.Add(b1);

onload

Series Navigation<< WPF: Code behind
WPF: Design the UI using designer >>

Leave a comment

Leave a Reply