Perform the following steps to create a ToolBox window and assign its ownership to the MainWindow, so that it can act according to its owner:
- Right-click on the project node and select Add | Window... from the context menu. The Add New Item dialog will be shown on the screen.
- Select Window (WPF) from the available list, give it the name ToolBox, and click Add to continue. This will add ToolBox.xaml and ToolBox.xaml.cs into your project.
- Open the ToolBox.xaml file and replace its content with the following XAML code:
<Window x:Class="CH01.OwnershipDemo.ToolBox" xmlns=
"http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" SizeToContent="WidthAndHeight" ResizeMode="NoResize" Title="ToolBox"> <StackPanel Margin="10"> <Button Content="Bold" Width="70" Margin="4"/> <Button Content="Italics" Width="70" Margin="4"/> <Button Content="Underlined" Width="70" Margin="4"/> </StackPanel> </Window>
- Now open the App.xaml page and remove the property attribute StartupUri, defined as (StartupUri="MainWindow.xaml") from it.
- Go to its code-behind file App.xaml.cs and override the OnStartup event. We need to modify the implementation according to our needs. Replace the entire OnStartup event handler with the following code block:
protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); var mainWindow = new MainWindow(); mainWindow.Show(); // must show before setting it
as owner of some other window var toolBox = new ToolBox { Owner = mainWindow }; toolBox.Show(); }
- Run the application to see the relationship between the two windows. The windows will look like the following screenshot:
- Drag the ToolBox window and you can see that you are able to move it outside the MainWindow. Now perform some operations, such as minimizing and closing, on the MainWindow, and you will see that the ToolBox window also acts according to its owner.