为什么标签在XAML TabControl的内容区显示选项卡标题?
-
22-07-2019 - |
题
我有一个的的TabControl 强>其ItemsSource绑定到视图强>(用户控件),其每个具有作为其根元素的的 TabItem的一个的观察集合STRONG>。然而,在显示时,在标题文字是在每个TabItem的内容,就好象的用户控件强>包装物引起冲突:
在的TabControl是的 SmartFormView.xaml:强>
<UserControl x:Class="TestApp.Views.SmartFormView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel
Margin="10">
<TextBlock Text="{Binding Title}"
FontSize="18"/>
<TextBlock Text="{Binding Description}"
FontSize="12"/>
<TabControl
Margin="0 10 0 0"
ItemsSource="{Binding SmartFormAreaViews}"/>
</StackPanel>
</UserControl>
我有什么改变,这样的TabItems显示为的TabControl内的TabItems?
下面是本TabItem的视图称为的 SmartFormAreaView.xaml:强>
<UserControl x:Class="TestApp.Views.SmartFormAreaView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<TabItem Header="This is the header">
<StackPanel Margin="10">
<TextBlock Text="this is the content"/>
</StackPanel>
</TabItem>
</UserControl>
和这里是创建和每个视图装入的的ObservableCollection 强>:
var areas = from area in xmlDoc.Descendants("area")
select area;
foreach (var area in areas)
{
SmartFormArea smartFormArea = new SmartFormArea();
smartFormArea.IdCode = area.Attribute("idCode").Value;
smartFormArea.Title = area.Attribute("title").Value;
SmartFormAreaPresenter smartFormAreaPresenter = new SmartFormAreaPresenter(smartFormArea);
SmartFormAreaViews.Add(smartFormAreaPresenter.View as SmartFormAreaView);
}
解决方案
有关任何ItemsControl的,如果添加到其相关文件集合中的项(直接或经由的ItemsSource)不是该控件的项容器的实例,则每个项目被包裹在物品容器的一个实例。物品容器是一类如TabItem的或ListBoxItem的。该项目容器通常是一个ContentControl中或HeaderedContentControl,和你实际的项目分配给它的内容属性,因此你可以使用模板等,以控制内容的呈现方式。您也可以使用ItemControl的ItemContainerStyle属性样式的项目容器本身。
在这个特定的情况下,应该结合的ItemsSource到SmartFormAreaPresenters的列表。然后使用类似这样的选项卡控制:
<TabControl ItemsSource="{Binding SmartFormAreaPresenters}">
<TabControl.ItemContainerStyle>
<Style TargetType="{x:Type TabItem}">
<Setter Property="Header" Value="{Binding HeaderText}" />
</Style>
</TabControl.ItemContainerStyle>
<TabControl.ContentTemplate>
<DataTemplate DataType="{x:Type local:SmartFormAreaPresenter}">
<local:SmartFormAreaView />
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
其中的HeaderText是在你SmartFormAreaPresenter合适的属性。你也应该从你的SmartFormAreaView定义中移除的TabItem。每个视图的DataContext的将被自动设置为合适的演示。
请参阅WPF博士的博客一个精彩讨论的各种ItemsControl的相关的主题。
其他提示
在TabControl
会接受您作为其控制控件,只有当他们可以转换为TabItem
,而不是用户控件,或SmartFormAreaView等。
让你无论是填写常规TabItems
用你的视觉树,或你的子类TabItems
,或者你的子类TabControl
覆盖其的 IsItemItsOwnContainerOverride
方法,接受您的类型作为容器。
的方法,应如下所示:
protected override bool IsItemItsOwnContainerOverride(object item)
{
return item is YourControlTypeHere || item is TabItem;
}