Binding to a WPF Listbox Part 2
In this example we will group the data in the WPF Listbox with CollectionView class. We will add a GroupStyle which will allow us to expand or hide the grouped data. We will start off by making a List which contains an Animals class. Then we create a ListCollectionView from the list. Finally we create an CollectionView from the ListCollectionView and add a GroupDescription to it. Then we bind the ListBox to the CollectionView
Pages XAML
<Window x:Class="Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<DataTemplate x:Key ="lstItem" >
<StackPanel>
<TextBlock Text="{Binding Path=Animal}"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
<Grid>
<ListBox Margin="14,15,47,34" Name="ListBox1" ItemTemplate="{StaticResource lstItem}" >
<ListBox.GroupStyle>
<GroupStyle>
<GroupStyle.ContainerStyle>
<Style 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" BorderBrush="#FFA4B97F"
BorderThickness="0,0,0,1">
<Expander.Header>
<DockPanel>
<TextBlock FontWeight="Bold" Text="{Binding Path=Name}"
Margin="5,0,0,0" Width="100"/>
<TextBlock FontWeight="Bold"
Text="{Binding Path=ItemCount}"/>
</DockPanel>
</Expander.Header>
<Expander.Content>
<ItemsPresenter />
</Expander.Content>
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
</ListBox.GroupStyle>
</ListBox>
</Grid>
</Window>
The Code
Class Window1
Private Sub Window1_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated
Dim lst As New List(Of Animals)
lst.Add(New Animals("Dog", "Mammal"))
lst.Add(New Animals("Parrot", "Bird"))
lst.Add(New Animals("Swordtail", "Fish"))
lst.Add(New Animals("Cat", "Mammal"))
lst.Add(New Animals("Falcon", "Bird"))
lst.Add(New Animals("Molly", "Fish"))
lst.Add(New Animals("Guppy", "Fish"))
lst.Add(New Animals("ferret", "Mammal"))
lst.Add(New Animals("Eagle", "Bird"))
Dim lcv As New ListCollectionView(lst)
Dim col As CollectionView
col = CollectionViewSource.GetDefaultView(lcv)
Dim groupDescription As PropertyGroupDescription = New PropertyGroupDescription
groupDescription.PropertyName = "Species"
col.GroupDescriptions.Add(groupDescription)
ListBox1.ItemsSource = col
End Sub
End Class
Public Class Animals
Private mstr_Animal As String
Public Property Animal() As String
Get
Return mstr_Animal
End Get
Set(ByVal value As String)
mstr_Animal = value
End Set
End Property
Private mstr_Species As String
Public Property Species() As String
Get
Return mstr_Species
End Get
Set(ByVal value As String)
mstr_Species = value
End Set
End Property
Public Sub New(ByVal Anml As String, ByVal spc As String)
mstr_Animal = Anml
mstr_Species = spc
End Sub
End Class