ListBox模板:如何创建通用模板,但仍根据项目更改内容 [英] ListBox templating: how to create a common template but still change content based on item
问题描述
我已经在WPF中将模板框模板化了一段时间,但是我想知道是否有一种方法可以为该ListBoxItem提供一个模板,该模板将应用于ListBox中的所有项目,但是还具有一个ItemTemplateSelector来更改内容的容器.
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.
我有一个字符串和图像的列表,我想唯一地显示它们,以便图像显示带有框架,字符串显示在要编辑的文本框中.我做了一个ItemTemplateSelector并根据类型选择了模板.但是我想添加一些控件,例如要删除的按钮和复选框以显示对两个模板的选择.
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?
推荐答案
您可以使用ItemContainerStyle
覆盖ListBoxItems
的Template
(可能不是我会做的事).
You could use the ItemContainerStyle
to override the Template
of the ListBoxItems
(probably not something i would do).
或者,您可以定义一个ItemTemplate
,该ItemTemplate
使用ContentControl
来构图您的模板,例如
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屋!