Using Multiple Windows in WPF Applications
This exercise introduces how you can use multiple windows in a Windows Presentation Foundation
(WPF) application.
Step1 Create Application
Create a new WPF application called MultiWindows.
…and then set up the user interface for the MainWindow as shown below.
Note: You may need to View->Toolbox to see the components.
Two buttons called
btnWindow1
btnWindow2
Content as shown
Step 2 Add new Windows.
In the solution explorer right click on the project and add two new Windows called Window1 and
Window2 (this should be the default names).
V3 3
Step 3 HCI for Windows Window1 and Window2
Set up the user interfaces for the two new windows similar to the ones below,
Each window should simply have a label to allow you to recognise which window is open.
Step 4 Opening a Window as a Dialog
Select the MainWindow.xaml design view and double click on the button btnWindow1 – this will
create the click event for you. Edit the code as shown below.
V3 3
Build and run the application and notice what happens when you click on the top button.
Step 5 Opening a Window as a normal window
This is slightly more work as we want the MainWindow to disappear and only appear again when the
window Window2 is closed.
Select the MainWindow design view and double click on the button btnWindow2 – this will create
the click event for you. Edit the code as shown below.
We now need to add some coding to the closing event of Window2 to re-open the MainWindow
when it is closed.
Step 5 Continued
Select the Window2 xaml file and select the Window. Now use the properties window to identify the
events that can be coded. The screen shot only shows a small number of available events.
Double click on the Closed event to create the event code outline automatically. Now edit the code
as shown below.
V3 3
Now run the program and note what happens.
Step 6 Closing Event
It would be nicer if the user was prompted to confirm that they want to close a Window. You can do
this using the closing event. Select Window2 and then use the properties window to create the
closing event handler by double clicking on the closing event. Now add in the following code.
Run the program and note what happens now.
Exercises
1. Add in appropriate closing events for the other two windows
2. Try creating another window and see if you can add a button to the MainWindow to open
the new Window as a normal window.
V3 3
Version history
Version Author/editor Changes
V2 AHart Updated for VS 2019
V3 Ahart Added project screen for VS2022. Added some
additional text and updated screenshots to show new
menus.
V3 3