WPF:如何在ComboBox中自定义SelectionBoxItem

And*_*kin 8 wpf customization templates combobox

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

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

Ray*_*rns 20

我会这样做:

<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="..."
  ... />
Run Code Online (Sandbox Code Playgroud)

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

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

  • 但是,这会生成一个绑定异常:`找不到与引用'RelativeSource FindAncestor绑定的源,AncestorType ='System.Windows.Controls.ComboBoxItem',AncestorLevel ='1''.我认为设置`ItemTemplateSelector`是一种更好的方法.这是一个例子:http://social.msdn.microsoft.com/Forums/vstudio/en-US/0467c9ca-efb2-4506-96e7-08ce3356860a/combobox-one-template-for-selected-item-one-for -the-下拉列表?论坛= WPF (2认同)