Reputation: 998
I've been templating ListBoxes for sometime in WPF, but I was wondering if there was a way to have a template for the ListBoxItem that would apply to all the items in the ListBox, but also have a ItemTemplateSelector to alter the contents of the containers.
I have a list of strings and images and I want to display them uniquely such that the image displays with a frame and strings display in a textbox to be edited. I made an ItemTemplateSelector and select the template based on the type. However I want to add some controls, like a button to delete and a checkbox to display selection to both templates.
I know I can add both objects to both templates for strings or images, but I want it to be able to scale and not have to added each time I add a template. Any thoughts?
Upvotes: 0
Views: 561
Reputation: 184441
You could use the ItemContainerStyle
to override the Template
of the ListBoxItems
(probably not something i would do).
Alternatively you can define a ItemTemplate
which frames your Templates by using a ContentControl
, e.g.
<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>
Upvotes: 1