The goal is to have a ComboBox whose ItemsSource should bind to more than one collection. In order to this, we make use of CompositeCollection as shown below.
XAML
<StackPanel>
<ComboBox Name="cb" ItemsSource="{Binding MoreThanOneCollection}">
</ComboBox>
</StackPanel>
Code-behind
Private _moreThanOneCollection As New CompositeCollection
Public Property MoreThanOneCollection() As CompositeCollection
Get
Return _moreThanOneCollection
End Get
Set(ByVal value As CompositeCollection)
_moreThanOneCollection = value
End Set
End Property
Private Sub Window_Loaded(ByVal sender As System.Object, _
ByVal e As System.Windows.RoutedEventArgs)
Me.DataContext = Me 'set the datacontext
BindData()
BindMoreData()
End Sub
Sub BindMoreData()
Dim data2 As New CollectionContainer
data2.Collection = GetData().Reverse()
'another set of data, just for the heck of it
MoreThanOneCollection.Insert(0, data2)
End Sub
Sub BindData()
Dim container = New CollectionContainer
container.Collection = GetData() ' the first data
MoreThanOneCollection.Add(container)
End Sub
Function GetData() As IEnumerable(Of String)
Dim x As New ObservableCollection(Of String)
x.Add("Item 1")
x.Add("Item 2")
x.Add("Item 3")
Return x
End Function
Just for practise purpose, I thought I would create the composite collection in code. This can also be done in XAML.
No comments:
Post a Comment