您可以使用ItemContainerStyle
覆盖ListBoxItems
的Template
(可能不是我会做的)。
或者,也可以定义一个ItemTemplate
,其利用ContentControl
,例如帧的模板
<ListBox ItemsSource="{Binding Data}">
<ListBox.Resources>
<!-- The frame that is applied to all items -->
<ControlTemplate x:Key="commonFrameTemplate" TargetType="{x:Type ContentControl}">
<Border BorderBrush="Red" BorderThickness="2" CornerRadius="5" Padding="5">
<StackPanel>
<CheckBox IsChecked="{Binding RelativeSource={RelativeSource AncestorType=ListBoxItem}, Path=IsSelected}"/>
<ContentPresenter /> <!-- Where the individual templates end up -->
<Button Content="Delete"/>
</StackPanel>
</Border>
</ControlTemplate>
<!-- Define templates without using a x:Key but setting the DataType,
the template will automatically be applied, no need for a
template-selector -->
<DataTemplate DataType="{x:Type local:Employee}">
<TextBlock Text="{Binding Name}" Foreground="Red"/>
</DataTemplate>
</ListBox.Resources>
<ListBox.ItemTemplate>
<DataTemplate>
<!-- By setting the content to {Binding} the templating is delegated
in a way, if you must use a selector, define one here as
ContentTemplateSelector -->
<ContentControl Template="{StaticResource commonFrameTemplate}"
Content="{Binding}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
这是一个很棒的想法。我的另一个想法是做一个用户控件,这是一个ContentControl中和其他地方定义它,但我觉得这正是我一直在寻找。我特别喜欢xaml接近模板,所以你可以告诉看看代码是什么。 – maschall 2011-05-04 13:41:32