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"
   Title="MainWindow" Height="350" Width="525">
   <Grid Name="myGrid">

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()

            Label myLabel = new Label();
            myLabel.Content = "Enter your Name: ";
            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;
            Button myButton = new Button();
            myButton.Content = "Submit";
            myButton.Height = 50;
            myButton.Width = 75;

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:


Download Complete Source Code


Leave a Reply