WPF控件模板和数据模板

3

我有一个 ListView,我想对它的项应用自定义的 ControlTemplate。它的定义如下:

<ListView ItemsSource="{Binding MyAwesomeItems}" ...

我的 MyAwesomeItems 包含不同的类。所以我自己想了一下:"嗯,DataTemplates 你好啊。"

为了让包含的项目看起来符合我的要求,我定义了一个 ControlTemplate 如下:

<ListView.ItemContainerStyle>
  <Style TargetType="ListViewItem">
    <Setter Property="Template">
      <Setter.Value>
        <ControlTemplate TargetType="ListViewItem">
          <Border><ContentControl Content="{TemplateBinding Content}"/></Border>
        </ControlTemplate>            
      </Setter.Value>
    </Setter>
  </Style>
</ListView.ItemContainerStyle>

我使用了ContentControl并带有绑定到TemplateBinding Content的方式。我期望WPF会将我的项目插入该ContentControl中,使用任何我为其定义的DataTemplate。

但实际上,它似乎只使用了项目.ToString(),并没有应用任何DataTemplates。这是预期的行为吗?

我想要实现的是:有一个项目列表,每个项目容器的外观都与我想要的完全相同,并且该容器的内容来自DataTemplate。


1
改用 ContentPresenter。区别在于 DataContext 的设置方式。 - Tobias Brandt
没关系,结果相同。 - Hemisphera
我忘了提醒:不要设置“Content”!只需使用<ContentPresenter/> - Tobias Brandt
太棒了!它可以工作。非常感谢。 - Hemisphera
要理解它为什么有效:https://msdn.microsoft.com/zh-cn/library/system.windows.controls.contentpresenter.contentsource(v=vs.110).aspx - Tobias Brandt
1个回答

2
ContentControlControlTemplate 中,通常会使用一个空的 ContentPresenter 标签。在您的情况下:
<ControlTemplate TargetType="ListViewItem">
    <Border>
        <ContentPresenter/>
    </Border>
</ControlTemplate>
ContentPresenter有一个ContentSource属性,默认值为“Content”,并设置所有必要的属性(ContentContentTemplate等)。
详情请参见此处

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接