WPF Combobox: Different template in textbox and drop-downlist

前端 未结 5 1243
面向向阳花
面向向阳花 2020-11-29 05:25

This is my combo-box.

    

        
5条回答
  •  一整个雨季
    2020-11-29 06:07

    Instead of using the read-only SelectionBoxItemTemplate property I created a new (attached, writable) property and used that one in my style. I also added a trigger to my style to not break all the comboboxes that are not using my new attached property...

    Use it like this:

    
        
            
                ... Template for the selection box ...
            
        
        
            
                ... Template for the popup ...
            
        
    
    

    You just have to add this class to your project:

    public class ComboBoxSelectionBoxAltTemplateBehaviour
    {
        public static readonly DependencyProperty SelectionBoxAltTemplateProperty = DependencyProperty.RegisterAttached(
            "SelectionBoxAltTemplate", typeof (DataTemplate), typeof (ComboBoxSelectionBoxAltTemplateBehaviour), new PropertyMetadata(default(DataTemplate)));
    
        public static void SetSelectionBoxAltTemplate(DependencyObject element, DataTemplate value)
        {
            element.SetValue(SelectionBoxAltTemplateProperty, value);
        }
    
        public static DataTemplate GetSelectionBoxAltTemplate(DependencyObject element)
        {
            return (DataTemplate) element.GetValue(SelectionBoxAltTemplateProperty);
        }
    
    }
    

    and change your ComboBox style to use the SelectionBoxAltTemplate attached property if set (or because I could not set a trigger to "not null", I set it back to the default SelectionBoxItemTemplate if the attached one is null):

    The ContentPresenter inside the ControlTemplate of the ComboBox Style:

    
    

    And the Trigger to provide backwards compatibility to ComboBoxed without the attached Property:

    
        
            
        
        ...
    
    

    Full Style:

    
    

    However this might not work with ItemTemplateSelctors, only with one single template - but you could easily add an attached property "SelectionBoxAltTemplateSelector" which provides the selector and passes that one to the style.

提交回复
热议问题