Reputation: 192
How to add ListView
Items via binding by Entity Framework / Linq?
I got my ListView
in the xaml with bindings here:
<ListView x:Name="lstvw_Overview" HorizontalAlignment="Left" Height="310" Margin="11,89,0,0" VerticalAlignment="Top" Width="676">
<ListView.View>
<GridView>
<GridViewColumn Header="Adresse" DisplayMemberBinding="{Binding address}"/>
</GridView>
</ListView.View>
</ListView>
This is my code
Public Sub New()
Initialize()
End Sub
Dim address As String
Dim items As ObservableCollection(Of Uebersicht)
Public Structure Uebersicht
Private _address As String
Public Property address As String
Get
Return _address
End Get
Set(value As String)
_address = value
End Set
End Property
End Structure
Sub Initialize()
InitializeComponent()
fillListView()
End Sub
Sub fillListView()
Using container As New infrastrukturDB_TESTEntities1
Dim mailAddressList = From tbl_unzustellbarAdressen In container.tbl_unzustellbarAdressen
For Each mail In mailAddressList
address = mail.unzustellbarMail.ToString()
Try
items.Add(New Uebersicht With {.address = address})
Catch ex As Exception
MessageBox.Show("Error")
End Try
Next
End Using
End Sub
EDIT: tried the ObserverableCollection
but now i got a NullReferenceException
!
If i debug, address got data.. not null
Upvotes: 1
Views: 990
Reputation: 169320
Since you are adding strings
to the ListView
, you should not bind to the address
property but the source object itself:
<ListView x:Name="lstvw_Overview" HorizontalAlignment="Left" Height="310" Margin="11,89,0,0" VerticalAlignment="Top" Width="676">
<ListView.View>
<GridView>
<GridViewColumn Header="Adresse" DisplayMemberBinding="{Binding}"/>
</GridView>
</ListView.View>
</ListView>
Edit: You need to intialize the ObservableCollection
before you can add items to it. And to be able to bind to the ObservableCollection
, you must expose it as a property:
Public Sub New()
Initialize()
End Sub
Dim address As String
Private _items As ObservableCollection(Of Uebersicht) = New ObservableCollection(Of Uebersicht)
Public Property Items As ObservableCollection(Of Uebersicht)
Get
Return _items
End Get
Set(value As ObservableCollection(Of Uebersicht))
_items = value
End Set
End Property
Sub Initialize()
InitializeComponent()
DataContext = Me
fillListView()
End Sub
XAML:
<ListView ItemsSource="{Binding Items}" HorizontalAlignment="Left" Height="310" Margin="11,89,0,0" VerticalAlignment="Top" Width="676">
<ListView.View>
<GridView>
<GridViewColumn Header="Adresse" DisplayMemberBinding="{Binding address}"/>
</GridView>
</ListView.View>
</ListView>
Upvotes: 4