WPF Combobox: Different template in textbox and drop-downlist

Viewed 33388

This is my combo-box.

    <ComboBox Height="45" HorizontalAlignment="Left" Margin="184,66,0,0" Name="ComboBox1" VerticalAlignment="Top" Width="216">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <Label Content="{Binding FullName}" Width="150" />
                    <Label Content="{Binding Title}" Width="100"/>
                    <Label Content="{Binding BranchName}" />
                </StackPanel>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>

How can I change it so that only the FullName appears in the textbox portion of the combobox while all three columns still appear in the drop-down portion?

5 Answers

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.

<controls:SelectionComboBox ItemsSource="{Binding ...}" SelectedItem="{Binding ..., Mode=TwoWay}">
    <controls:SelectionComboBox.AltSelectionBoxItemTemplate>
        <DataTemplate>
            <!-- My Template Goes Here... -->
        </DataTemplate>
    </controls:SelectionComboBox.AltSelectionBoxItemTemplate>
</controls:SelectionComboBox>
Related