ComboBox ItemTemplate only working in dropdown

前端 未结 2 656
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-31 02:20

I am trying to show a ComboBox whose ItemsSource is a collection of Controls (it is part of a PropertyGrid, the ComboBox should display the names of the controls, and the us

相关标签:
2条回答
  • 2020-12-31 02:40

    Use DisplayMemberPath instead of binding to name:

     <Combobox DisplayMemberPath="Name" ... />
    

    The reason for the behaviour you see probably is that you need to set another property for selected item's template: http://msdn.microsoft.com/en-us/library/system.windows.controls.combobox.selectionboxitemtemplate.aspx


    Update: I've written my answer without checking your code, sorry for that. Now I've read your code and noticed that you're binding SelectedValue property. I do no think this is the best property to bind in your case, usually property SelectedItem should be used. I remember that I never had to do anything with SelectionBoxItem stuff mentioned in other answer, that's probably because SelectedValue and SelectedItem properties behave differently and I tend to use SelectedItem whenever I can. In your case I would use it too.

    0 讨论(0)
  • 2020-12-31 02:54

    The ComboBox, for some very complex reasons exposes a read-only property called SelectionBoxItem. The content presenter in the ComboBox template binds on this property. It is the SelectionBoxItem that exposes the string representation of non-UI elements allowing you to see the selected value. The use of this property is what prevents the content presenter from using data templates. This is why the template applies to the drop down but not the selected item. Here is the part of the default ComboBox template causing the issue:

    <ContentPresenter IsHitTestVisible="false"
        Margin="8,1,1,1"
        Content="{TemplateBinding SelectionBoxItem}"
        ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}"
        ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}"
        VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
        HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
        SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
    

    You can however create your own ComboBox style that overrides the default ContentPresenter and uses the SelectedItem instead of SelectionBoxItem and ItemTemplate instead of SelectionItemBoxTemplate. This will resolve the issue.

    0 讨论(0)
提交回复
热议问题