WPF DataGrid的GroupStyle上的HeaderTemplate和ContainerStyle有什么区别?

Jul*_*ius 6 wpf xaml datagrid .net-3.5 groupstyle

似乎ContainerStyle优先使用它们HeaderTemplate时指定两者,如下所示;

<controls:DataGrid.GroupStyle>
  <GroupStyle>
    <GroupStyle.HeaderTemplate>
      <DataTemplate>
        <StackPanel>
          <TextBlock Text="{Binding Path=Name}" Background="Yellow" />
        </StackPanel>
      </DataTemplate>
    </GroupStyle.HeaderTemplate>
    <GroupStyle.ContainerStyle>
      <Style TargetType="{x:Type GroupItem}">
        <Setter Property="Template">
          <Setter.Value>
            <ControlTemplate TargetType="{x:Type GroupItem}">
              <Expander IsExpanded="true" Background="Violet">
                <Expander.Header>
                  <DockPanel TextBlock.FontWeight="Bold">
                    <TextBlock Text="{Binding Path=Name}" />
                    <TextBlock Text="{Binding Path=ItemCount}"/>
                  </DockPanel>
                </Expander.Header>
                <ItemsPresenter />
              </Expander>
            </ControlTemplate>
          </Setter.Value>
        </Setter>
      </Style>
    </GroupStyle.ContainerStyle>
  </GroupStyle>
</controls:DataGrid.GroupStyle>
Run Code Online (Sandbox Code Playgroud)

唯一的区别是HeaderTemplate无法访问ItemsPresenter,或与分层数据结构有什么区别?

谢谢!

编辑链接到http://wpftutorial.net/DataGrid.html#grouping.我实际上并没有直接从那里拿到这个例子,但它是一个很棒的网站,所以无论如何他们都可以拥有一个链接.

She*_*dan 8

该GroupStyle.HeaderTemplate属性允许您设置a DataTemplate以定义DataGrid将在其中显示的组标题.这是标题通常出现在每个组顶部的部分.

来自MSDN:

获取或设置用于显示组头的模板.

该GroupStyle.ContainerStyle属性允许您添加一个Style定义每个组项的容器的外观.可以把它想象成每个组项目所在的"框".在这种情况下,框内的数据看起来像是由一个DataTemplate集合定义为DataGrid.ItemsTemplate.

来自MSDN:

允许应用程序编写者为要应用于每个生成的样式提供自定义选择逻辑GroupItem.

更新>>>

回应你的评论......你应该看到两者.我猜你的代码来自WPF Tutorials.NET上的WPF DataGrid Control文章(除非你想侵犯他们的版权,否则你真的应该链接到这个)这是你的问题......他们没有ContainerStyle正确实现.

为了更准确,他们还没有实现ControlTemplate在ContainerStyle正确.当您定义a时ControlTemplate,通常会添加一个ContentPresenter内部来"呈现内容",在这种情况下来自DataTemplate于内容HeaderTemplate.如果添加一个,您将看到两个模板都在工作:

<ControlTemplate TargetType="{x:Type GroupItem}">
    <Expander IsExpanded="true" Background="Violet">
        <Expander.Header>
            <DockPanel TextBlock.FontWeight="Bold">
                <ContentPresenter /> 
            </DockPanel>
        </Expander.Header>
        <ItemsPresenter />
    </Expander>
</ControlTemplate>
Run Code Online (Sandbox Code Playgroud)

试着记住这个:

绑定到DataTemplates中的数据类型属性...线索在名称中.

再次定义s ... 的Control样子ControlTemplate,线索......名字.

  • 默认情况下,GroupItem 的模板是否有一个由 HeaderTemplate 填充的标题占位符,但如果您覆盖 GroupItem 的模板并且不为标题提供占位符,那么它将不会被使用? (2认同)