Wpf 基于画布的ItemsControl的ItemContainerStyle
我有以下ItemsControl,我使用画布作为面板:Wpf 基于画布的ItemsControl的ItemContainerStyle,wpf,wpf-controls,datatemplate,itemscontrol,Wpf,Wpf Controls,Datatemplate,Itemscontrol,我有以下ItemsControl,我使用画布作为面板: <ItemsControl ItemsSource="{Binding Widgets}"> <ItemsControl.Resources> <DataTemplate DataType="{x:Type widgetLayoutSpike:ColouredWidget}"> <Grid Background="{Binding BgColour}"
<ItemsControl ItemsSource="{Binding Widgets}">
<ItemsControl.Resources>
<DataTemplate DataType="{x:Type widgetLayoutSpike:ColouredWidget}">
<Grid Background="{Binding BgColour}">
<TextBlock Text="{Binding Title}" />
</Grid>
</DataTemplate>
</ItemsControl.Resources>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<Grid Background="Yellow">
<!-- <ContentPresenter /> -->
</Grid>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
我的要求是:
- ItemTemplates是通过类型化的DataTemplates设置的(上面显示了一个用于着色Widget项类型的示例)。对于不同的项目类型,可能会有几种
- 我需要能够指定一个ItemContainer模板,它包装了所有不同的ItemTemplates。具体的使用案例是,我希望这个ItemContainer为所有项目(带有按钮等)设置一个公共边框
提前谢谢 使用ListBox而不是ItemsControl可能更容易做到这一点,因为容器类型是
ListBoxItem
,它(与ContentPresenter相反)有一个控件模板,您可以在样式中替换该模板:
<ListBox ItemsSource="{Binding Widgets}">
<ListBox.Resources>
<DataTemplate DataType="{x:Type widgetLayoutSpike:ColouredWidget}">
<Grid Background="{Binding BgColour}">
<TextBlock Text="{Binding Title}" />
</Grid>
</DataTemplate>
</ListBox.Resources>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Grid Background="Yellow">
<ContentPresenter Margin="2"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
编辑:也许你必须写作
<ContentPresenter Margin="2"
Content="{TemplateBinding Content}"
ContentTemplate="{TemplateBinding ContentTemplate}"/>
您应该为ItemControl定义一个样式,在那里您可以通过触发器动态设置ItemTemplate和ItemContainerStyle。这似乎合乎逻辑,但这只是为每个项目呈现一个ListBoxItem,然后是黄色网格和一个空的ContentPresenter。它不再拾取数据模板。在我的测试程序中,它拾取数据模板。您确定这些项目是coloredwidget
对象吗?