WPF ItemsControl vs contentControl问题

时间:2011-04-20 17:39:18

标签: wpf

希望有些WPF忍者可以向我解释为什么我有一个标签控件,在我的标签中我将内容(在本例中为用户控件)放入ItemsControl或ContentControl中,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"/>

感谢!!!

2 个答案:

答案 0 :(得分:11)

ContentControl旨在显示单个内容。默认情况下,它会拉伸以填充整个包含区域,ContentControl内的内容将会拉伸以填充它。

ItemsControl,如名称所示,旨在在其中显示多个项目。它将填充其包含的区域,但添加的内容项只会占用他们需要的空间。这是因为它旨在允许添加多个项目 - 如果第一个项目被拉伸以填满空间,则稍后添加的其他项目将没有“空间”。

答案 1 :(得分:2)

Reed声明的是正确的,但您可以更改ItemsControl的行为(编辑ItemTemplate以使其默认占用所有可用高度)。但是,我不确定这是一个好主意(因为它意味着能够容纳多个项目)。

相关问题