[英]Why are tab headers displayed in the content area of tabs in a XAML TabControl?
我有一個TabControl,其ItemsSource綁定到一個可觀察的視圖集合 (UserControls),每個視圖都有一個TabItem作為其根元素。 但是,當它顯示時, Header文本位於每個TabItem的內容中,就像UserControl包裝器導致沖突一樣:
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);
}
對於任何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。
有關各種ItemsControl相關主題的精彩討論,請參閱WPF博士的博客 。
只有將TabControl
為TabItem
,而不是UserControl或SmartFormAreaView等時, TabControl
才會接受控件作為控件。
因此,您可以使用可視樹填充常規TabItems
,或者IsItemItsOwnContainerOverride
TabItems
子類,或者IsItemItsOwnContainerOverride
TabControl
以覆蓋其IsItemItsOwnContainerOverride
方法,以接受您的類型作為容器。
該方法應如下所示:
protected override bool IsItemItsOwnContainerOverride(object item)
{
return item is YourControlTypeHere || item is TabItem;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.