Different template for items in ComboBox's drop-down list and for selected item

前端 未结 2 1233
刺人心
刺人心 2020-12-09 11:01

I have a ComboBox with fairly complex template for individual items, which includes two images and several lines of text:

2条回答
  •  悲哀的现实
    2020-12-09 11:40

    I was searching for a standard (not hacky and without binding errors) solution to this problem. And I found it here: using DataTemplateSelector.

    It's the same idea as per @H.B. answer: check whenever there is a ComboBoxItem as a parent in visual tree.

    public class ComboBoxItemTemplateSelector : DataTemplateSelector
    {
        public DataTemplate SelectedTemplate { get; set; }
        public DataTemplate DropDownTemplate { get; set; }
    
        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            while (container != null)
            {
                container = VisualTreeHelper.GetParent(container);
                if (container is ComboBoxItem)
                    return DropDownTemplate;
            }
            return SelectedTemplate;
        }
    }
    

    Usage:

    
        
            
                
                    ... simple template for selected item
                
            
            
                
                    ... complex template used by dropdown items
                
            
        
    
    

提交回复
热议问题