问题
I have the following XAML Code:
<sdk:DataGrid Margin="58,8,52,18" Name="dataGridTickets">
<sdk:DataGrid.Columns>
<sdk:DataGridTextColumn x:Name="ticketNoColumn" Header="Ticket No." IsReadOnly="True" Width="SizeToHeader"/>
<sdk:DataGridTextColumn x:Name="seatRowColumn" Header="Seat Row" IsReadOnly="True" Width="SizeToHeader"/>
<sdk:DataGridTextColumn x:Name="seatNumberColumn" Header="Seat Number" IsReadOnly="True" Width="SizeToHeader"/>
</sdk:DataGrid.Columns>
</sdk:DataGrid>
I would like to enter manual data into the grid programatically, how can I manage to do this?
Thanks
Working Solution
Programatically add rows in a WPF DataGrid
回答1:
You don't add rows to a grid.
- Bind the Grid to a List (Observable collection)
- Add items to that list.
Result: new rows show up in the grid.
回答2:
If you don't want to databind the datagrid (even at runtime), you can follow the advice in this SO article:
programmatically add column & rows to WPF Datagrid
Basically you create a new row (in code) and populate it with items and then assign it to your grid.
Like Henk pointed out though, it isn't a great practice. If this is a one-off situation, there may be justification for it but in general you should approach it by updating the underlying data source. Here is an example from Microsoft:
http://social.msdn.microsoft.com/Forums/en/wpf/thread/9b96a798-e185-4d90-ba73-afc35eb91643
来源:https://stackoverflow.com/questions/6011444/manually-add-rows-in-wpf-datagrid