views:

109

answers:

1

I want to have a wpf combobox that displays the dropdown list box with the options grouped under a heading like the <optgroup> behaviour in html. Has anyone seem something like this done before?

A: 

See How to: Sort and Group Data Using a View in XAML. You apply a grouping to the CollectionView for your data and then set the GroupStyle on the ComboBox. Done entirely XAML, it would look like this:

<StackPanel>
    <StackPanel.Resources>
        <CollectionViewSource x:Key="groupedData" Source="{Binding}">
            <CollectionViewSource.GroupDescriptions>
                <PropertyGroupDescription PropertyName="Length"/>
            </CollectionViewSource.GroupDescriptions>
        </CollectionViewSource>
    </StackPanel.Resources>
    <ComboBox ItemsSource="{Binding Source={StaticResource groupedData}}">
        <ItemsControl.GroupStyle>
            <x:Static Member="GroupStyle.Default"/>
        </ItemsControl.GroupStyle>
    </ComboBox>
</StackPanel>

Or you could apply the grouping in code:

this.DataContext = new List<string>() { "foo", "barr", "baz", "fizz" };
var cv = CollectionViewSource.GetDefaultView(this.DataContext);
cv.GroupDescriptions.Add(new PropertyGroupDescription("Length"));

And use the default collection view in Xaml:

<ComboBox ItemsSource="{Binding}">
    <ItemsControl.GroupStyle>
        <x:Static Member="GroupStyle.Default"/>
    </ItemsControl.GroupStyle>
</ComboBox>

You could customize the look of the grouped data by providing a custom GroupStyle with your own HeaderTemplate.

Quartermeister