为什么选项卡标题显示在XAML TabControl的选项卡的内容区域中?

问题描述 投票:3回答:2

我有一个TabControl,其ItemsSource绑定到一个可观察的视图集合(UserControls),每个视图都有一个TabItem作为其根元素。但是,当它显示时,Header文本位于每个TabItem的内容中,就像UserControl包装器导致冲突一样:

alt text

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?

以下是名为SmartFormAreaView.xaml的TabItem视图:

<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);
}
c# wpf xaml mvp tabcontrol
2个回答
4
投票

对于任何ItemsControl,如果添加到其Items集合中的项目(直接或通过ItemsSource)不是该控件的项容器的实例,则每个项目都包含在项目容器的实例中。 item容器是一个类,如TabItem或ListBoxItem。项容器通常是ContentControl或HeaderedContentControl,并且您的实际项目已分配给其Content属性,因此您可以使用模板等来控制内容的呈现方式。您还可以使用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。每个View的DataContext将自动设置为适当的Presenter。

请参阅WPF博士的blog,以便对各种ItemsControl相关主题进行精彩讨论。


0
投票

TabControl将接受您的控件作为其控件,只有它们可以转换为TabItem,而不是UserControl或SmartFormAreaView等。

所以你要么用你的视觉树填充常规TabItems,要么你继承qa​​zxswpoi,或者你继承qa​​zxswpoi来覆盖它的TabItems方法,接受你的类型作为容器。

该方法应如下所示:

TabControl
© www.soinside.com 2019 - 2024. All rights reserved.