I’m still teaching myself how to bind and use observable collection. One problem that I’m a little confused on is binding multiple classes/observable collection to one page. In other words, if I have a PersonName class and a AnimalName class, I have to create two separate observalbe collections for each? How would I set the datacontext when a page only allows one?
For example:
Public Class NameList
Inherits ObservableCollection(Of PersonName)
' Methods
Public Sub New()
MyBase.Add(New PersonName("Willa", "Cather"))
MyBase.Add(New PersonName("Isak", "Dinesen"))
MyBase.Add(New PersonName("Victor", "Hugo"))
MyBase.Add(New PersonName("Jules", "Verne"))
End Sub
End Class
Public Class PersonName
' Methods
Public Sub New(ByVal first As String, ByVal last As String)
Me._firstName = first
Me._lastName = last
End Sub
' Properties
Public Property FirstName() As String
Get
Return Me._firstName
End Get
Set(ByVal value As String)
Me._firstName = value
End Set
End Property
Public Property LastName() As String
Get
Return Me._lastName
End Get
Set(ByVal value As String)
Me._lastName = value
End Set
End Property
' Fields
Private _firstName As String
Private _lastName As String
End Class
Now If I add another class, how would I combine the two on the binding part and collection part. Thanks for any advice 🙂
public class AnimalName
'properties, ect...ect..ect..
End class
You need to make the object which you set as the DataContext to be another class which contains the collection of people and the collection of animals. Then your controls which display the lists can bind their ItemsSource properties to the relevant properties in the DataContext, such as
You can’t add them both to the same collection unless it’s a collection of some type that they both derive from (ultimately everything derives from Object), but then you have to deal with how to render them appropriately in the UI.
Also although the page has a DataContext, everything inside it has a DataContext too, so you can bind those individually – otherwise they just inherit the DataContext from their parent.