Manually add rows in WPF DataGrid

折月煮酒 提交于 2021-01-27 04:06:52

问题


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.

  1. Bind the Grid to a List (Observable collection)
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!