在MVVM中设计动态行标题,列标题和内容

时间:2013-06-25 07:18:14

标签: c# wpf datagrid datatable datarow

我想要一个itemsource,它提供了MVVM模式中列标题,行标题及其内容的绑定。我已经尝试过DataTable,但是,我不知道如何填充行标题。在添加DataRow?

期间可以填充行头
DataRow dr = new DataRow();
dr.ItemArray = current.Split(new char[] { '\t' });
// add row header?

请帮忙。

1 个答案:

答案 0 :(得分:-1)

这是你想要的吗?

XAML代码:

<Grid>
    <DataGrid Name="SimpleDataGrid" AutoGenerateColumns="True" ItemsSource="{Binding}" />
</Grid>

创建新数据行:

private void CreateNewDataRow()
{
    // Use the MakeTable function below to create a new table.
    DataTable table;
    table = MakeNamesTable();

    // Once a table has been created, use the  
    // NewRow to create a DataRow.
    DataRow row;
    row = table.NewRow();

    // Then add the new row to the collection.
    row["fName"] = "John";
    row["lName"] = "Smith";
    table.Rows.Add(row);

    foreach (DataColumn column in table.Columns)
    {
        Console.WriteLine(column.ColumnName);
    }

    SimpleDataGrid.DataContext = table;
}

创建新列:

private DataTable MakeNamesTable()
{
    // Create a new DataTable titled 'Names.'
    DataTable namesTable = new DataTable("Names");

    // Add three column objects to the table.
    DataColumn idColumn = new DataColumn();
    idColumn.DataType = System.Type.GetType("System.Int32");
    idColumn.ColumnName = "id";
    idColumn.AutoIncrement = true;
    namesTable.Columns.Add(idColumn);

    DataColumn fNameColumn = new DataColumn();
    fNameColumn.DataType = System.Type.GetType("System.String");
    fNameColumn.ColumnName = "Fname";
    fNameColumn.DefaultValue = "Fname";
    namesTable.Columns.Add(fNameColumn);

    DataColumn lNameColumn = new DataColumn();
    lNameColumn.DataType = System.Type.GetType("System.String");
    lNameColumn.ColumnName = "LName";
    namesTable.Columns.Add(lNameColumn);

    // Create an array for DataColumn objects.
    DataColumn[] keys = new DataColumn[1];
    keys[0] = idColumn;
    namesTable.PrimaryKey = keys;

    // Return the new DataTable. 
    return namesTable;
}

调用CreatingNewDataRow():

public MainWindow()
{
   InitializeComponent();

   CreateNewDataRow();
}

有关详细信息,请参阅:

DataRow Class MSDN

DataTable.NewRow Method MSDN