c# - WPF 控件模板和数据模板

标签 c# wpf datatemplate controltemplate

我有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绑定(bind)到 TemplateBinding Content .我希望 WPF 然后将我的项目插入到 ContentControl 中,使用我为其定义的任何 DataTemplate。

但是,WPF 似乎只使用项目 .ToString()并且不应用任何数据模板。这是有意为之的行为吗?

我想要实现的是:拥有一个项目列表,其中每个项目的容器看起来和我想要的完全一样,内容 来自 DataTemplate。

最佳答案

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

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

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

参见 here了解详情。

关于c# - WPF 控件模板和数据模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32089575/

相关文章:

wpf - 在 WPF 中的另一个数据模板中使用一个数据模板

c# - 使用 Azure Active Directory 进行身份验证时进行 Azure 管理库 API 调用时出错

c# - 如何截取WPF控件的屏幕截图?

c# - 将数据模板元素绑定(bind)到子类的属性

c# - 在它的 "taking a screenshot"之前等待 UI 重绘

c# - WPF Treeview HierarchicalDataTemplate ItemTemplateSelector

c# - 具有基于类型的数据模板选择和绑定(bind)的 Contentpresenter

c# - 静态方法和线程

c# - 查询数据库出错

c# - 数据库中的值在文本框中不可见,请将值插入到正确的用户名中