ListBox templates: how to create a common template, but still change the content based on the element

I use Template for ListBoxes sometime in WPF, but I was wondering if there is a way to create a template for ListBoxItem that will apply to all items in ListBox, but also has an ItemTemplateSelector to modify the contents of containers.

I have a list of lines and images, and I want to show them uniquely, so that the image is displayed with the frame and lines displayed in the text box for editing. I created an ItemTemplateSelector and select a template based on the type. However, I want to add some controls, such as a button for deletion, and a check box to display a selection for both templates.

I know that I can add both objects to both templates for strings or images, but I want it to be scalable and not added every time a template is added. Any thoughts?

0
source share
1 answer

You can use ItemContainerStyleto override Templatein ListBoxItems(maybe this is not what I would do).

Alternatively, you can determine ItemTemplatewhich forms your templates using ContentControl, for example

<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>
+1
source

All Articles