Elmo
Elmo

Reputation: 6471

Display ComboBoxItems in Multiple Columns

I want my ComboBox to display ComboBoxItems in multiple columns like this:

Can someone tell me how can I do this?

I can use this:

        <ComboBox.ItemsPanel>
            <ItemsPanelTemplate>
                <UniformGrid Columns="3"/>
            </ItemsPanelTemplate>
        </ComboBox.ItemsPanel>

But it doesn't let me specify where I want to end a column.

Is there a way to make the ComboBox use the Grid.Column property in the ComboBoxItems so that I can add the ComboBoxItems in different columns?

Upvotes: 3

Views: 209

Answers (2)

Barracoder
Barracoder

Reputation: 3764

Change the ItemsPanelTemplate to a WrapPanel.

<ComboBox>
    <ComboBox.Resources>
        <Style TargetType="ComboBox">
            <Setter Property="ItemsPanel">
                <Setter.Value>
                    <ItemsPanelTemplate>
                        <WrapPanel IsItemsHost="True" Orientation="Vertical" Width="100" Height="50" />
                    </ItemsPanelTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        <Style TargetType="ComboBoxItem">
            <Setter Property="Width" Value="50" />
        </Style>
    </ComboBox.Resources>

    <ComboBoxItem Content="Item 1" />
    <ComboBoxItem Content="Item 2" />
    <ComboBoxItem Content="Item 3" />
    <ComboBoxItem Content="Item 4" />
    <ComboBoxItem Content="Item 5" />
    <ComboBoxItem Content="Item 5" />

</ComboBox>

Upvotes: 1

Sheridan
Sheridan

Reputation: 69987

You'll need to add a custom Panel to your project and set it as the ItemsPanel like this:

<ComboBox>
    <ComboBox.ItemsPanel>
        <ItemsPanelTemplate>
            <Controls:ColumnPanel />
        </ItemsPanelTemplate>
    </ComboBox.ItemsPanel>
</ComboBox>

You can find out how to create custom Panels in this tutorial.

EDIT >>>

I've just thought that you might be able to get this simple layout from an existing Panel: the WrapPanel... give me a moment while I investigate this.

Further EDIT >>>

Ok, so there are these properties on a WrapPanel; ItemWidth and ItemHeight. This is a bit of a hack, but if you set the ItemWidth property of the WrapPanel to half of the Width of the WrapPanel, then you'll have a basic two column Panel. The only problem is that you'll have to hard code these values.

Personally, I would recommend taking the time to create a simple re-usable ColumnPanel control that allows you to set how many columns that you want in it. I have one and have found many uses for it... they can also go into ListBox and other collection controls.

Upvotes: 0

Related Questions