WPF Combobox: Different template in textbox and drop-downlist

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

This is my combo-box.

    

        
5条回答
  •  难免孤独
    2020-11-29 06:04

    You could override the ComboBox and change the SelectionBoxItemTemplate directly.

    public class SelectionComboBox : ComboBox
    {
        #region Properties
    
        #region Dependency Properties
        public DataTemplate AltSelectionBoxItemTemplate
        {
            get { return (DataTemplate)GetValue(AltSelectionBoxItemTemplateProperty); }
            set { SetValue(AltSelectionBoxItemTemplateProperty, value); }
        }
    
        public static readonly DependencyProperty AltSelectionBoxItemTemplateProperty =
            DependencyProperty.Register("AltSelectionBoxItemTemplate", typeof(DataTemplate), typeof(SelectionComboBox), new UIPropertyMetadata(null, (s, e) =>
            {
                // For new changes...
                if ((s is SelectionComboBox) && ((SelectionComboBox)s).Presenter != null && (e.NewValue is DataTemplate))
                    ((SelectionComboBox)s).Presenter.ContentTemplate = (DataTemplate)e.NewValue;
    
                // Set the new value
                ((SelectionComboBox)s).AltSelectionBoxItemTemplate = (DataTemplate)e.NewValue;
            }));
        #endregion
    
        #region Internals
    
        #region Elements
        ContentPresenter Presenter { get; set; }
        #endregion
    
        #endregion
    
        #endregion
    
        #region Constructors
        #endregion
    
        #region Methods
    
        #region Overrides
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
    
            Presenter = this.GetTemplateChild("contentPresenter") as ContentPresenter;
    
            // Directly Set the selected item template
            if (AltSelectionBoxItemTemplate != null) Presenter.ContentTemplate = AltSelectionBoxItemTemplate;
        }
        #endregion
    
        #endregion
    
    }
    

    Once you define the control, you could style it.

    
        
            
                
            
        
    
    

提交回复
热议问题