ListBox 模板:如何创建通用模板但仍根据项目更改内容 [英] ListBox templating: how to create a common template but still change content based on item

查看:10
本文介绍了ListBox 模板:如何创建通用模板但仍根据项目更改内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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?

解决方案

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>

这篇关于ListBox 模板:如何创建通用模板但仍根据项目更改内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆