Create a New Window in WPF

Introduction

In this blog, we will learn basics of Windows in WPF and how create a Window in WPF using C#.  

Follow the below steps to create a new window in WPF:

Step 1: Create an empty WPF using Visual Studio, enter the name for the application and click on OK.

Step 2: Create a button using the following code or drag and drop a button from the ToolBox of Visual Studio 2013.

Code:

  1. <Button Content="Button" HorizontalAlignment="Left" Margin="133,120,0,0" VerticalAlignment="Top" Width="75"/>  

 

Step 3: Solution Name(Right Click) --> Add à New Window.

Step 4: Name the New window and click on OK.

Step 5: Name the New window and click on OK.

Code:

  1. <TextBox HorizontalAlignment="Left" Height="23" Margin="119,98,0,0" TextWrapping="Wrap"Text="TextBox" VerticalAlignment="Top" Width="120"/>  

 

Rename the Text if you need

Now move to MainWindow.xaml and double click on the Button, enter the following code

  1. Newwindow p = Newwindow();  
  2.   
  3. p.Show();  

Code for Mainwindow.xaml.cs is:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using System.Windows;  
  7. using System.Windows.Controls;  
  8. using System.Windows.Data;  
  9. using System.Windows.Documents;  
  10. using System.Windows.Input;  
  11. using System.Windows.Media;  
  12. using System.Windows.Media.Imaging;  
  13. using System.Windows.Navigation;  
  14. using System.Windows.Shapes;  
  15. namespace newwindow.xaml  
  16. {  
  17.     /// <summary>  
  18.     /// Interaction logic for MainWindow.xaml  
  19.     /// </summary>  
  20.     public partial class MainWindow: Window  
  21.     {  
  22.         public MainWindow()  
  23.         {  
  24.             InitializeComponent();  
  25.         }  
  26.         private void Button_Click(object sender, RoutedEventArgs e)  
  27.         {  
  28.             Newwindow p = Newwindow();  
  29.             p.Show();  
  30.         }  
  31.     }  
  32. }  

Now run the program.