数据模板未在ItemContainer中注入

时间:2009-11-14 19:19:01

标签: wpf datatemplate itemscontrol

我有一个ItemsControl类,它会覆盖以下方法:

protected override bool IsItemItsOwnContainerOverride(object item)
{
    return item is TilePanelItem;
}

protected override DependencyObject GetContainerForItemOverride()
{
    return new TilePanelItem();
}

我提供了TilePanelItem的模板,它是ItemsControl的容器:

<ControlTemplate x:Key="tileItemTemplate" TargetType="my:TilePanelItem">
    <Grid Width="200" Height="100">
        <Border BorderBrush="Black" BorderThickness="2">
            <ContentPresenter RenderTransformOrigin=".5,.5" />    
        </Border>
    </Grid>
</ControlTemplate>

它的Style

<Style TargetType="my:TilePanelItem">
    <Setter Property="Template" Value="{StaticResource tileItemTemplate}" />
</Style>

最后我的ItemsControl的实例与DataTemplate

<my:TileItemsControl x:Name="tileControl" ItemsSource="{Binding}" >
    <my:TileItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel />
        </ItemsPanelTemplate>
    </my:TileItemsControl.ItemsPanel>
    <my:TileItemsControl.ItemTemplate>
        <DataTemplate>
            <Border Background="Blue">
                <TextBlock Text="here I am" />
            </Border>
        </DataTemplate>
    </my:TileItemsControl.ItemTemplate>
</my:TileItemsControl>

我定义的DataTemplate未在ItemContainer中注入。当我运行应用时,它会显示我在ItemContainter模板中声明的边框,但我看不到DataTemplate

我错过了什么?

万分感谢

1 个答案:

答案 0 :(得分:0)

您需要将ItemsTemplate置于ContentPresenter的ContentTemplate中:

<ControlTemplate x:Key="tileItemTemplate" TargetType="my:TilePanelItem">
  <Grid Width="200" Height="100">
    <Border BorderBrush="Black" BorderThickness="2">
      <ContentPresenter RenderTransformOrigin=".5,.5"
        ContentTemplate="{Binding ItemsTemplate, RelativeSource={RelativeSource FindAncestor,my:TileItemsControl,1}}" />
    </Border>
  </Grid>
</ControlTemplate>