Wpf 为ItemsControl.ItemContainerStyle指定ControlTemplate
以下内容与我试图完成的内容类似。然而,我得到了错误 无效的PropertyDescriptor值 在模板Wpf 为ItemsControl.ItemContainerStyle指定ControlTemplate,wpf,itemscontrol,controltemplate,itemcontainerstyle,Wpf,Itemscontrol,Controltemplate,Itemcontainerstyle,以下内容与我试图完成的内容类似。然而,我得到了错误 无效的PropertyDescriptor值 在模板Setter上。我怀疑这是因为我没有为样式指定TargetType;但是,我不知道ItemsControl的容器类型 <ItemsControl> <ItemsControl.ItemContainerStyle> <Style> <Setter Property="Template">
Setter
上。我怀疑这是因为我没有为样式指定TargetType
;但是,我不知道ItemsControl
的容器类型
<ItemsControl>
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<StackPanel>
<TextBlock Text="Some Content Here" />
<ContentPresenter />
<Button Content="Edit" />
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ItemsControl.ItemContainerStyle>
<!-- heterogenous controls -->
<ItemsControl.Items>
<Button Content="Content 1" />
<TextBox Text="Content 2" />
<Label Content="Content 3" />
</ItemsControl.Items>
</ItemsControl>
您可以使用类型名称限定属性名称:
<Setter Property="Control.Template">
您还需要在ControlTemplate
上设置TargetType
,以便ContentPresenter
将绑定到Content
属性:
<ControlTemplate TargetType="ContentControl">
另外,如果您只想使用XAML完成所有操作,您只需使用ListBox而不是ItemsControl,并为ListBoxItem定义一个样式:
<ListBox ItemsSource="{Binding Elements.ListViewModels}">
<ListBox.Resources>
<Style TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<StackPanel>
<TextBlock>Some Content Here</TextBlock>
<ContentPresenter Content="{TemplateBinding Content}" />
<Button>Edit</Button>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.Resources>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
<Style TargetType="ListBoxItem">
这里有一些内容
编辑
请注意,因为我使用的是ListBox,所以容器是ListBoxItem(通常WPF默认列表控件的容器总是命名为Item),所以我们为ListBoxItem创建了一个样式:
<ListBox ItemsSource="{Binding Elements.ListViewModels}">
<ListBox.Resources>
<Style TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<StackPanel>
<TextBlock>Some Content Here</TextBlock>
<ContentPresenter Content="{TemplateBinding Content}" />
<Button>Edit</Button>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.Resources>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
<Style TargetType="ListBoxItem">
然后我们为ListBoxItem创建一个新的ControlTemplate。请注意,ContentPresenter在文章和教程中不经常使用,您需要将其模板绑定到ListBoxItem的内容属性,以便它显示该项目的内容
<ContentPresenter Content="{TemplateBinding Content}" />
我只是遇到了同样的问题,并通过这种方式解决了它。我不想要ListBox(项目选择)的一些功能,通过使用这种技术,项目选择不再有效。工作顺利!我试着用XAML来完成所有的工作,只需几行代码就可以派生一个类,这一切都很愉快、整洁和干净。“如果您添加了UIElement以外的项目,该setter将在ContentPresenter上设置Control.Template属性,这将成功,但没有任何效果。”-我找了很久才发现这个技巧!