繁体   English   中英

如何将WPF窗口作为TabControl项加载到MainWindow中?

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

我的MainWindow.xaml的结构如下

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

问题是我的MainWindow.xaml当前是大约4000行代码,效率不高(您同意吗?)我要实现的解决方案是分别创建N个窗口(代表我的TabItem),每次用户单击时在Tab项目上,我在该TabItem中加载相关窗口,如下所示

 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");
        }

我现在遇到错误,“'Management_V0.Inventory'根元素对于导航无效。”

窗口不能是另一个元素的子级。 期。

但是,你可能只是移动的内容Inventory窗口的UserControl (例如通过简单的复制和粘贴的XAML和从一个文件到另一个代码),并用这一个作为Content的的Inventory窗口和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();

使用tabControl的最佳方法是通过用户控件:下例:XAML

 <TabControl >
                <TabItem x:Name="tab1" Header="UserControl"></TabItem>
                <TabItem x:Name="tab2" Header="noControl"></TabItem>
            </TabControl>

在类后面的代码中:

  tab1.Content = new UserControl1();

然后添加名为UserControl1的新用户控件:

<UserControl x:Class="WpfApplication1.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <Viewbox>
            <TextBlock Text="User Control"/>
        </Viewbox>
    </Grid>
</UserControl>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM