WPF ItemsControl vs contentControl问题

Ken*_*enn 2 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);
}
Run Code Online (Sandbox Code Playgroud)

这是窗口的XAML.

 <Grid>
    <TabControl Name="MyTab">

    </TabControl>
</Grid>
Run Code Online (Sandbox Code Playgroud)

这是用户控件 - 只有标签......

<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"/>
Run Code Online (Sandbox Code Playgroud)

谢谢!!!

Ree*_*sey 11

ContentControl旨在显示单个内容.默认情况下,它将拉伸以填充其整个包含区域,并且ContentControl将拉伸内容以填充它.

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