【问题标题】:WPF ControlTemplate AND DataTemplateWPF 控件模板和数据模板
【发布时间】:2015-08-19 07:52:16
【问题描述】:

我有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 然后使用我为它定义的任何 DataTemplate 将我的项目插入到 ContentControl 中。

但相反,WPF 似乎只使用项目 .ToString() 并且不应用任何 DataTemplates。这是预期的行为吗?

我想要实现的是:拥有一个项目列表,其中每个项目的容器看起来完全符合我的要求,并且内容 strong> 该容器来自 DataTemplate。

【问题讨论】:

  • 改用ContentPresenter。区别在于DataContext 的设置方式。
  • 没关系。结果相同。
  • 我忘了说:不要设置Content!只需使用&lt;ContentPresenter/&gt;
  • 太棒了!有用。非常感谢。
  • 要了解它的工作原理:msdn.microsoft.com/en-us/library/…

标签: c# wpf datatemplate controltemplate


【解决方案1】:

ControlTemplateContentControl 中,您通常使用空的ContentPresenter 标记。在你的情况下:

<ControlTemplate TargetType="ListViewItem">
    <Border>
        <ContentPresenter/>
    </Border>
</ControlTemplate>

ContentPresenter 有一个 ContentSource 属性,默认为“内容”并设置所有必要的属性(ContentContentTemplate 等)。

详情请见here

【讨论】:

    猜你喜欢
    • 2020-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多