wpf - 组合框下拉列表中的项目和选定项目的不同模板

标签 wpf xaml datatemplate

我有一个 ComboBox单个项目的模板相当复杂,其中包括两个图像和几行文本:

enter image description here

但是,ComboBox 中的选定项本身不能正确显示,因为垂直空间太有限(我不能让它更高,因为它是 ToolBar 的一部分)。

如何使 ComboBox 对 ComboBox 中显示的项目使用不同的模板本身? (默认 ToString 表示就可以了)

谢谢!

最佳答案

所选项目(在 ComboBox 本身中,而不是下拉列表中)不在 ComboBoxItem 中所以你可以做这样的事情:

<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>

( 编辑: 请注意,选择框中的绑定(bind)会抛出错误,因为找不到 RelativeSource。有多种方法可以规避这一点,其中一种是返回 true 的自定义值转换器。或 false 取决于祖先是否存在(手动树行走)。)

关于wpf - 组合框下拉列表中的项目和选定项目的不同模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8279107/

相关文章:

c# - 从事件触发器内更改属性

c# - 通过循环将项目添加到 DataContext

wpf - 我应该使用 DataTemplates 还是 UserControl 来显示扩展类的不同控件?

c# - 微软下的正则表达式

c# - OnMouseMove() 事件处理委托(delegate)

c# - 如何为 gridview 项目(文本 block )提供动态宽度?

c# - 在 ListView ItemTemplate 填充中制作网格

c# - 我如何使用约定实现 Caliburn.Micro 操作的延迟

c# - 将数据从数据表显示到数据网格时出现 System.outofmemoryexception

c# - 如何在 WPF 中转换