2011-04-20 76 views
2

希望一些WPF忍者可以向我解釋爲什麼如果我有一個選項卡控件,並且在我的選項卡中我將內容(在這種情況下是一個用戶控件)放入ItemsControl或ContentControl中,contentControl中的內容將展開並填滿整個屏幕,但如果它在項目控制中,它不會......我認爲這個例子會使這個更清晰。WPF ItemsControl vs contentControl問題

public MainWindow() 
{ 
    InitializeComponent(); 

    //This content won't expand to fill the available space 
    var t1 = new TabItem(); 
    t1.Header = "Tab One"; 
    var ic = new ItemsControl(); 
    ic.Items.Add(new UserControl1()); 
    t1.Content = ic; 

    //in this case the label will fill up the whole window... 
    var t2 = new TabItem(); 
    t2.Header = "Tab Two"; 
    var c = new ContentControl(); 
    c.Content = new UserControl1(); 
    t2.Content = c; 

    MyTab.Items.Add(t1); 
    MyTab.Items.Add(t2); 
} 

這裏是窗口的XAML。

<Grid> 
    <TabControl Name="MyTab"> 

    </TabControl> 
</Grid> 

這裏是用戶控制 - 不過是一個標籤...

<UserControl x:Class="TabControlTest.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" Background="Red"> 
<Label Content="User control one"/> 

謝謝!

回答

10

ContentControl旨在顯示單個內容。默認情況下,它將伸展以填充其整個包含區域,並且ContentControl內的內容將伸展以填充它。

ItemsControl,如名稱所示,意味着在其中顯示多個項目。它將填充其包含的區域,但添加的內容項僅佔用它們所需的空間。這是因爲它旨在允許添加多個單個項目 - 如果第一個項目拉伸以填充空間,則稍後添加的其他項目不會有「空間」。

+0

Opps - 我想我應該已經更清楚了......如果你看看項目控制和內容控制的繼承,他們都繼承了Control ...我認爲這與它沒有任何關係? Danny Varod躲過了導致這種行爲的模板嗎? – Kenn 2011-04-20 18:04:41

2

Reed說的是正確的,但是您可以更改ItemsControl的行爲(編輯ItemTemplate以使其佔用所有可用高度)。但是,我不確定這是一個好主意(因爲它意味着可以容納多個項目)。