在WPF数据网格中手动添加行

时间:2016-05-27 02:32:20

标签: c# wpf datagrid

我正在编写需要在WPF上使用节点和连接器的项目。 我的节点和连接器类是

public class Node
{
    private string _nodeId;
    private string _nodeType;
    private double _x;
    private double _y;
    /*
    set/get function here
    */
}


public class Connector
{
    private string _startNodeId;
    private string _endNodeId;
    /*
    set/get function here
    */
}

我想使用datagrid列出所有连接器,如下所示

-----------------------------------------
|       |   01  |   02  |   03  |   04  |
-----------------------------------------
|   01  |   x   |   1   |   0   |   1   |
-----------------------------------------
|   02  |   0   |   x   |   0   |   1   |
-----------------------------------------
|   03  |   1   |   1   |   x   |   1   |
-----------------------------------------
|   04  |   1   |   1   |   0   |   x   |
-----------------------------------------

在datagrid上,列和行标题是节点列表中的节点ID。所以我需要手动向datagrid添加行。我经常搜索,但没有运气。

任何人都可以帮助我。谢谢!

1 个答案:

答案 0 :(得分:0)

为什么不将数据网格的data source创建为数据表,然后在后面的代码中分配源代码。请参阅下面的代码。

    // Create a datatable for your datagrid's source
    DataTable datatbl = new DataTable();
    datatbl.Columns.Add("startNode_ID", typeof(int));
    datatbl.Columns.Add("endNode_ID", typeof(int));

    // You can add new rows to datatable here
    for (int iCount = 1; iCount < MaximumRequiredCount; iCount++)
    {
        var row = datatbl.NewRow();
        row["startNode_ID"] = Your Start Node ID;
        row["endNode_ID"] = Your End Node ID;
        datatbl.Rows.AddRow(row);
    }

    DataGridView dataGrid1 = new DataGridView();
    dataGrid1.AutoGenerateColumns = true;
    dataGrid1.DataSource = datatbl;

在xaml中设置绑定

<DataGrid Name="dataGrid1" ItemsSource="{Binding}">