WPF:如何在 ComboBox 中自定义 SelectionBoxItem [英] WPF: How to customize SelectionBoxItem in ComboBox

查看:26
本文介绍了WPF:如何在 ComboBox 中自定义 SelectionBoxItem的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将自定义模板/项目显示为 ComboBox 中的选定项目(该项目实际上并不存在于项目列表中,并且更新方式不同).这甚至不需要是一个项目,只需提供自定义视图即可.

I want to display a custom template/item as selected item in ComboBox (this item does not actually exist in the list of items and is updated differently). This does not even needs to be an item, just providing a custom view would work.

如何在保持当前 ComboBox 主题的同时执行此操作(因此无法替换 ControlTemplate)?据我所知,所有 SelectionBox* 属性都是不可编辑的,并且内部 ComboBox 使用未命名的 ContentPresenter.

How can I do this while staying within current ComboBox theme (so no ControlTemplate replacement possible)? As far as I see, all of SelectionBox* properties are not editable and internally ComboBox uses unnamed ContentPresenter.

推荐答案

我会这样做:

<Window.Resources>

  <DataTemplate x:Key="NormalItemTemplate" ...>
    ...
  </DataTemplate>

  <DataTemplate x:Key="SelectionBoxTemplate" ...>
    ...
  </DataTemplate>

  <DataTemplate x:Key="CombinedTemplate">
    <ContentPresenter x:Name="Presenter"
       Content="{Binding}"
       ContentTemplate="{StaticResource NormalItemTemplate}" />
    <DataTemplate.Triggers>
      <DataTrigger
        Binding="{Binding RelativeSource={RelativeSource FindAncestor,ComboBoxItem,1}}"
        Value="{x:Null}">
        <Setter TargetName="Presenter" Property="ContentTemplate"
                Value="{StaticResource SelectionBoxTemplate}" />
      </DataTrigger>
    </DataTemplate.Triggers>
  </DataTemplate>

</Window.Resources>

...

<ComboBox
  ItemTemplate="{StaticResource CombinedTemplate}"
  ItemsSource="..."
  ... />

这样做的原因是 CombinedTemplate 通常只使用 NormalItemTemplate 来呈现它的数据,但是如果没有 ComboBoxItem 祖先它假定它在选择框中,所以它使用 SelectionBoxTemplate.

The reason this works is that CombinedTemplate normally just uses NormalItemTemplate to present its data, but if there is no ComboBoxItem ancestor it assumes it is in the selection box so it uses SelectionBoxTemplate.

请注意,三个 DataTemplates 可以包含在 ResourceDictionary 的任何级别(不仅仅是在 Window 级别)中,甚至可以直接包含在ComboBox,取决于您的喜好.

Note that the three DataTemplates could be included in any level of ResourceDictionary (not just at the Window level) or even directly within the ComboBox, depending on your preference.

这篇关于WPF:如何在 ComboBox 中自定义 SelectionBoxItem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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