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

查看:1789
本文介绍了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 窗口级别),甚至直接在 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天全站免登陆