Search code examples
c#wpfxamlframetabitem

How to Load a WPF window in the MainWindow as a TabControl item?


The structure of my MainWindow.xaml is as bellow

<Window>
   <Grid>
    <TabControl Name="MainTabCntrl">
       <TabItem1>
       <TabItem2>
       <TabItem3>
       .
       .
       .
       <TabItemN>
    </TabControl>
   </Grid>
</Window>

The problem is that my MainWindow.xaml is currently ~4000 lines of code,which is not efficient(do you agree?) the solution I'm trying to implement is to create N windows (representing my TabItems) separately and each time user click on Tab items I load the related windows in that TabItem as shown bellow

 private void inventory_start()//this function is called in my MainWinodw.xaml.cs
        {
            inv = new Inventory(db, logViewer);//this is a window
            TabItem tbItem = new TabItem();
            Frame frame = new Frame();
            frame.Content = inv;
            tbItem.Name = "invTab";
            tbItem.Content = frame;
            tbItem.IsSelected = true;
            MainTabCntrl.Items.Add(tbItem);
            inv.swithInventoryTabs("inv_info");
        }

I have an error now , "'Management_V0.Inventory' root element is not valid for navigation."


Solution

  • A window cannot be a child of another element. Period.

    But you could just move the contents of the Inventory window to a UserControl (by for example simply copy and paste the XAML and the code from one file to another) and use this one as the Content of the Inventory window and the Frame:

    <Window x:Class="WpfApplication1.Inventory"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:WpfApplication1"
            mc:Ignorable="d"
            Title="Inventory" Height="300" Width="300">
        <local:UserControl1 />
    </Window>
    

    Frame frame = new Frame();
    frame.Content = new UserControl1();