Reputation: 469
I was able to find an example of a grouped combobox here http://www.jarloo.com/wpf-combobox-with-groupings/
Its perfect for my use except I need an additional behavior. The items should all be collapsible under their respective headers (Using expanders).
For eg. Fruit Apple Orange Grape Animals Cat Dog Cow
The above items will be displayed in a combobox in a grouped style but I will like each headers (Here it would be Fruit, Animals) to be collapsible using an expander. Could you please help with an example?
Thanks, Chev
Upvotes: 0
Views: 1917
Reputation: 2185
What you want is a TreeView instead of a ComboBox
. The WPF TreeView
natively supports this behavior. Example from MSDN below.
Note: This doesn't have the dropdown functionality you were looking for.
Your code would look like this:
<TreeView SelectedItemChanged="TreeView_SelectedItemChanged">
<TreeViewItem Header="Fruit">
<TreeViewItem Header="Apple"/>
<TreeViewItem Header="Orange"/>
<TreeViewItem Header="Grape"/>
</TreeViewItem>
<TreeViewItem Header="Animals">
<TreeViewItem Header="Cat"/>
<TreeViewItem Header="Dog"/>
<TreeViewItem Header="Cow"/>
</TreeViewItem>
</TreeView>
Edit: Added additional code to prevent the user from clicking on the header items, and instead it just collapses/expands the node.
private void TreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
var item = e.NewValue as TreeViewItem;
if (item == null ||item.Items.Count == 0) return;
item.IsExpanded = !item.IsExpanded;
item.IsSelected = false;
}
Edit: And here id a preview of what that would look like
Upvotes: 0
Reputation: 929
Try this
<Grid>
<Grid.Resources>
<Style x:Key="GroupItem" TargetType="{x:Type GroupItem}">
<Setter Property="Margin" Value="0,0,0,5"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Expander IsExpanded="True">
<Expander.Header>
<DockPanel>
<TextBlock Text="{Binding Name}" FontWeight="Bold" Margin="2,5,0,2" FontSize="14"/>
</DockPanel>
</Expander.Header>
<Expander.Content>
<Border Margin="5,0,0,0">
<ItemsPresenter />
</Border>
</Expander.Content>
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Grid.Resources>
<ComboBox Height="27" HorizontalAlignment="Left" Margin="162,109,0,0" VerticalAlignment="Top" Width="195" DisplayMemberPath="Item" Name="cboGroup">
<ComboBox.GroupStyle>
<GroupStyle ContainerStyle="{StaticResource GroupItem}"/>
</ComboBox.GroupStyle>
</ComboBox>
</Grid>
Upvotes: 3