I've been struggling with datagrid
databinding
for days now..
I am trying to generate datagrid
dynamically from a list
of custom objects.
Because the number of list-object properties that I need to display might change, I don't know exact number of columns, nor their headers.
So I thought, I'd dynamically add only the columns I need and create bindings (to the specific object properties) for them. After that I would fill in the datagrid
with data from a list
based on the bindings.
For example:
I create an empty datagrid
<DataGrid x:Name="MyDataGrid" AutoGenerateColumns="false" ItemsSource="{Binding}" Margin="0,0,0,31" Grid.RowSpan="2">
</DataGrid>
I create my list, to store my data and the data object:
Public Class Res
Public Shared TableData As New List(Of DataItem)
End Class
Public Class DataItem
Public Property Name() As String
Public Property MyProperty() As String
Public Property Prop() As String
Public Property Prop1() As String
End Class
Now, say I want to show only the Name
column in my datagrid
, so I add a column with specific binding (presumably this is where the problem lies, yet I can't figure it out):
Dim col As New DataGridTextColumn
Dim bb As New Binding
bb.Path = New PropertyPath("Name")
bb.Mode = BindingMode.TwoWay
bb.Source = Res.TableData
col.Binding = bb
col.Header = "Name"
MyDataGrid.Columns.Add(col)
Then, I finally create and add some data to my list:
Dim entry As New DataItem
entry.Name = "Test Name"
entry.MyProperty = "Test Property"
entry.Prop = "one Entry"
Res.TableData.Add(entry)
Me.MyDataGrid.ItemsSource = Res.TableData
Now the result is, that the entire column is filled with that same data. Where my intention was to fill only the row that corresponds to the exact list
item. For example, if I later want to add another item to the list
with a different "Name" it should be shown in the datagrid
as another row with a different "Name" as well.
I would suggest you to bind your grid to your List property, have AutoGenerateColumns = True and listen to AutoGeneratingColumn there you decide if you want to add that column to grid or not.