WPF: How to customize SelectionBoxItem in ComboBox

前端 未结 4 712
执念已碎
执念已碎 2020-12-01 19:48

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

4条回答
  •  再見小時候
    2020-12-01 20:04

    Alexey Mitev's comment on Ray Burns' answer inspired me to write the following reasonably short utility class, which I now use in all my WPF projects:

    public class ComboBoxItemTemplateSelector : DataTemplateSelector
    {
        public List SelectedItemTemplates { get; } = new List();
        public List DropDownItemTemplates { get; } = new List();
    
        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            return GetVisualParent(container) == null
                ? ChooseFrom(SelectedItemTemplates, item)
                : ChooseFrom(DropDownItemTemplates, item);
        }
    
        private static DataTemplate ChooseFrom(IEnumerable templates, object item)
        {
            if (item == null)
                return null;
            var targetType = item.GetType();
            return templates.FirstOrDefault(t => (t.DataType as Type) == targetType);
        }
    
        private static T GetVisualParent(DependencyObject child) where T : Visual
        {
            while (child != null && !(child is T))
                child = VisualTreeHelper.GetParent(child);
            return child as T;
        }
    }
    

    With that in the toolbox, it's possible to write XAML like this:

    
         
             
         
    
         
             
         
    
         
             
         
    
         
             
         
    
    
    
        
            
                
                    
                    
                
    
                
                    
                    
                
            
        
    
    

提交回复
热议问题