ComboBox的下拉列表中的项目和所选项目的不同模板
我有一个 ComboBox
,其中包含用于单个项目的相当复杂的模板,其中包括两个图像和几行文本:
I have a ComboBox
with fairly complex template for individual items, which includes two images and several lines of text:
但是, ComboBox
本身中的所选项目无法正确显示,因为垂直空间太有限(我不能使其更高,因为它是 ToolBar )。
However, the selected item in the ComboBox
itself doesn't display correctly, because the vertical space is too limited (I can't make it higher, because it is a part of a ToolBar
).
如何使ComboBox对显示在其中的项目使用不同的模板 ComboBox
本身?(默认的 ToString
表示就可以了)
How can I make the ComboBox use a different template for the item which is displayed in the ComboBox
itself? (the default ToString
representation would do just fine)
谢谢!
所选项目(在 ComboBox
本身(而不是下拉列表)不在 ComboBoxItem
内,因此您可以执行以下操作:
The selected item (in the ComboBox
itself, not the dropdown) is not inside a ComboBoxItem
so you can do something like this:
<ComboBox.ItemTemplate>
<DataTemplate>
<ContentControl Content="{Binding}">
<ContentControl.Style>
<Style TargetType="{x:Type ContentControl}">
<!-- Complex default template -->
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<Image Source="{Binding XPath=media:thumbnail/@url}" Width="100" Height="100" />
</DataTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<!-- Simple selection box template -->
<DataTrigger
Binding="{Binding RelativeSource={RelativeSource AncestorType=ComboBoxItem}}"
Value="{x:Null}">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<TextBlock Text="{Binding XPath=title}" />
</DataTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
</DataTemplate>
</ComboBox.ItemTemplate>
(编辑:请注意,选择框中的绑定将因为找不到 RelativeSource
而引发错误,有多种方法可以绕开它,一种是返回 true $ c $的自定义值转换器c>或
false
,具体取决于祖先是否存在(手动步行)。
( Note that the binding in the for the selection box will throw errors because the RelativeSource
is not found. There are various options of circumventing this, one being a custom value converter that returns true
or false
depending on whether the ancestor exists (manual tree walking).)