是否可以将TabItem放入单独的XAML中,并引用如下内容:
<TabControl>
<local:MyTabItem/>
</TabControl>
In Separate XAML:
<UserControl x:Class="MyProject.MyTabItem"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<TabItem Header="MyTab">
</TabItem>
</UserControl>
当然不行,但是我想知道如何才能做到这一点?
最佳答案
如果您只是想使代码更易于管理,那么我建议您在用户控件中定义每个选项卡的数据,但主选项卡控件中仍应具有TabItem。
假设您的原始代码是这样的:
<TabControl>
<TabItem Header="Tab 1">
<Grid>
<TextBlock Text="Tab Data" />
</Grid>
</TabItem>
</TabControl>
为了使代码更易于管理,您可以将选项卡内容分成一个UserControl,例如:
<UserControl x:Class="WpfApplication19.Tab1Data"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>
<Grid>
<TextBlock Text="Tab Data" />
</Grid>
</UserControl>
然后像这样在TabControl中使用该用户控件:
<TabControl>
<TabItem Header="Tab 1">
<tabData:Tab1Data />
</TabItem>
</TabControl>
如果您确实想在用户控件中包含TabItem,则可以通过以下方式进行操作:首先创建一个用户控件,然后将用户控件的类型更改为TabItem类型(请确保在xaml根节点和后面的代码)。
这将为您提供一个如下所示的选项卡控件:
<TabControl>
<tabData:TabItem1 />
<tabData:TabItem2 />
<tabData:TabItem3 />
</TabControl>
每个TabItem1“用户控件”的类型均为TabItem。这是一个例子:
<TabItem x:Class="WpfApplication19.TabItem1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Header="Tab 1"
>
<Grid>
<TextBlock Text="Tab Data" />
</Grid>
</TabItem>
正如我提到的,请确保更改后面的代码,以使其扩展TabItem而不是用户控制:
public partial class TabItem1 : TabItem
{
public TabItem1()
{
InitializeComponent();
}
}
关于wpf - 单独的XAML中的TabItem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1590031/