7

我有以下代码:

 <Window.Resources>      
       <DataTemplate x:Key="SectionTemplate" >                          
              <TextBlock Text="{Binding Path=Name}" />                  
       </DataTemplate>
 </Window.Resources>
 <Grid >        
   <Border>
       <HeaderedItemsControl Header="Top1"
                             ItemsSource="{Binding Path=List1}" 
                             ItemTemplate="{StaticResource SectionTemplate}"/>
    </Border>       
 </Grid>
public class MainWindow
{
   public List<Item> List1
   {
      get { return list1; }
      set { list1 = value; }
   }

   public MainWindow()
   {             
      list1.Add(new Item { Name = "abc" });
      list1.Add(new Item { Name = "xxx" });

      this.DataContext = this;      
      InitializeComponent();       
   }   
}

public class Item
{     
    public string Name { get; set; }
}

由于某种原因,Items它们被渲染,但没有标题。

4

2 回答 2

9

正如文档指出的那样:

HeaderedItemsControl 具有有限的默认样式。要创建具有自定义外观的 HeaderedItemsControl,请创建一个新的ControlTemplate

因此,当您创建该模板时,请确保包含一些ContentPresenter绑定到Header(例如使用ContentSource

例如

<HeaderedItemsControl.Template>
    <ControlTemplate TargetType="{x:Type HeaderedItemsControl}">
        <Border>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition />
                </Grid.RowDefinitions>
                <ContentPresenter ContentSource="Header" />
                <Separator Grid.Row="1" />
                <ItemsPresenter Grid.Row="2" />
            </Grid>
        </Border>                       
    </ControlTemplate>
</HeaderedItemsControl.Template>

所有默认绑定(边距、背景等)都被省略了。

于 2011-08-28T12:52:32.597 回答
0

您可以DataTemplate为标题制作一个,就像您为项目所做的那样(这肯定比重做整个控件模板的侵入性要小)。

例如

<Window.Resources>
  <DataTemplate x:Key="HeaderTemplate">
  </DataTemplate>
</Window.Resources>

<HeaderedItemsControl Header="Top1"
                      HeaderTemplate="{StaticResource HeaderTemplate}"
                      ItemsSource="{Binding Path=List1}"
                      ItemTemplate="{StaticResource SectionTemplate}"
                      />

您可以绑定到一个对象,然后在 DataTemplate 中使用相对于该对象的绑定,而不是像这里那样使用“Top1”。

这种方法有一个问题,那就是为非控制元素(特别是TextBlock)引入样式的必要方法有点复杂。另请参阅WPF 某些样式未应用于 DataTemplate 控件。(您也可能在使用 ControlTemplate 方法时遇到这种情况。)

于 2020-02-24T20:48:54.767 回答