How to Add Controls Programmatically in WPF Application?

Updated on     Kisan Patel

This tutorial will explain you learn how to add controls to a WPF application through the code-behind file.

Lets create new WPF application and name it “WPFAddControlDemo” and replace Grid element with the below code in the MainWindow.xaml file.

<Window x:Class="WPFAddControlDemo.MainWindow"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   Title="MainWindow" Height="350" Width="525">
   <Grid Name="myGrid">
   
   </Grid>
</Window>

In above code, you can see we have apply the name of the Grid control to myGrid. The controls will be added to the Grid control from your code-behind file. Therefore, open the MainWindow.xaml.cs file and add code shown in below code.

using System.Windows;
using System.Windows.Controls;

namespace WPFAddControlDemo
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            Label myLabel = new Label();
            myLabel.Content = "Enter your Name: ";
            myGrid.Children.Add(myLabel);
            TextBox myTextBox = new TextBox();
            myTextBox.Margin = new Thickness(0, 10, 20, 0);
            myTextBox.Height = 30;
            myTextBox.Width = 150;
            myTextBox.HorizontalAlignment = HorizontalAlignment.Right;
            myTextBox.VerticalAlignment = VerticalAlignment.Top;
            myGrid.Children.Add(myTextBox);
            Button myButton = new Button();
            myButton.Content = "Submit";
            myButton.Height = 50;
            myButton.Width = 75;
            myGrid.Children.Add(myButton);
        }
    }
}

After adding the controls and setting their properties, as shown in above code. Now, run the application by pressing the F5 key. The output will be:

Add-control-code-behind

Download Complete Source Code


WPF

Leave a Reply