我有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()
并且不应用任何数据模板。这是有意为之的行为吗?
我想要实现的是:拥有一个项目列表,其中每个项目的容器看起来和我想要的完全一样,内容该容器的 strong> 来自 DataTemplate。
最佳答案
在 ContentControl
的 ControlTemplate
中,您通常使用空的 ContentPresenter
标签。在你的情况下:
<ControlTemplate TargetType="ListViewItem">
<Border>
<ContentPresenter/>
</Border>
</ControlTemplate>
ContentPresenter
有一个 ContentSource
属性,默认为“Content”并设置所有必要的属性(Content
、ContentTemplate
等)。
参见 here了解详情。
关于c# - WPF 控件模板和数据模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32089575/