To create a new window, follow these simple steps:
- Open the Solution Explorer and right-click on the project node.
- From the right-click context menu, navigate to Add | Window... as shown in the following screenshot:
- The following Add New Item dialog will appear on the screen:
- Make sure that the selected template is Window (WPF). Give it a name, SecondWindow.xaml, and click the Add button.
- This will create the SecondWindow.xaml file and its associated code-behind file SecondWindow.xaml.cs in the project directory.
- Open the XAML file (SecondWindow.xaml) and replace the entire contents with the following XAML code:
<Window x:Class="CH01.WindowDemo.SecondWindow" xmlns=
"http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Second Window" Height="200" Width="300"> <Grid> <TextBlock Text="Second Window Instance" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="16"/> </Grid> </Window>
- Now open the MainWindow.xaml file to add a button into it. Replace the entire <Grid> </Grid> block, with the following XAML code:
<Grid> <Button Content="Open Second Window" Height="30" Width="150" Click="OnSecondWindowButtonClicked"/> </Grid>
- Now we need to add the implementation for the button-click event. Simply open the MainWindow.xaml.cs file and add the following lines of code inside the class definition:
private void OnSecondWindowButtonClicked(object sender, RoutedEventArgs e) { var window = new SecondWindow(); window.Show(); }
- Now, when you run the application, you will see that the MainWindow opens on the screen, containing a button labeled Open Second Window. Clicking on this button opens the second window on the screen that has text content of Second Window Instance. Here's the screenshot for your reference:
Please note that if you click the button again, it will create another instance of the second window because it's modeless.