Search code examples
wpfvb.netdatagridwpfdatagrid

Trying to bind a list of objects to a WPF datagrid control and seeing blank lines


I am stuck and need some help. I have spent a full day trying to sort this one out. I have read a lot of examples of how this should be done and it appears that I have done it correctly but clearly I have missed something. I have a blank form with one button and one datagrid. When I click the button I want to load a list of points into the datagrid control. The data must be getting loaded because I see three blank lines in the grid (no headers), but no data. Help please! Thanks!

Class MainWindow

Class Point
    Public Inc As String
    Public AZ As String
    Public MD As String
    Public TD As String
End Class


Private Sub Button_Click(sender As Object, e As RoutedEventArgs)

    Dim mySurvey As New List(Of Point)
    Dim myPoint1 As New Point
    Dim myPoint2 As New Point

    myPoint1.AZ = "1"
    myPoint1.Inc = "2"
    myPoint1.MD = "100"
    myPoint1.TD = "98"

    myPoint2.AZ = "10"
    myPoint2.Inc = "20"
    myPoint2.MD = "1000"
    Point2.TD = "980"


    mySurvey.Add(myPoint1)
    mySurvey.Add(myPoint2)
    dgSurvey.ItemsSource = mySurvey

End Sub

End Class

XAML

<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
    <Button Content="Button" HorizontalAlignment="Left" Height="28" Margin="45,30,0,0" VerticalAlignment="Top" Width="57" Click="Button_Click"/>
    <DataGrid x:Name="dgSurvey" HorizontalAlignment="Left" Margin="45,78,0,0" VerticalAlignment="Top" Height="172" Width="275"/>

</Grid>


Solution

  • For binding to work you should define properties in your Point class, not public fields. This is explicitly stated in MSDN: Binding Sources Overview:

    The properties you use as binding source properties for a binding must be public properties of your class. Explicitly defined interface properties cannot be accessed for binding purposes, nor can protected, private, internal, or virtual properties that have no base implementation.

    You cannot bind to public fields.