如何向 DataGrid 添加列?

How to add columns to a DataGrid?

我基于 this other question 来显示一个包含一些列的 DataGrid(还没有要填充的行,只有列):

我有以下源代码:

cs 文件:

public partial class MainWindow : Window
{
    private DataTable dt_main;
    ...
}

private ...first_Click(object sender, ...)
{
    dt_main = new DataTable("dt_main"); // just a default name, no such table
    DataGrid1.DataContext = dt_main.DefaultView;
}

private ...second_Click(object sender, ...)
{
    dt_main.Columns.Clear();
    ...
    while (...)
      dt_main.Columns.Add(tmp_ColName);
}

XAML 文件:

<DataGrid x:Name="DataGrid1" ... AutoGenerateColumns="True" ItemsSource="{Binding}"/>

我点击 first_click(这是为了填充 table 的列表),然后点击 second_click(这是为了选择 table),但是尽管填写了 DataTable 的 Columns 属性,但我在我的 DataGrid 中看不到任何内容,正如您在下面的屏幕截图中看到的那样(DataGrid 由红色箭头显示):

有人知道我错过了什么吗?

这些列仅在实际设置 ItemsSource 属性 时自动生成。

在将列添加到 DataTable 后显式设置它,或者将列添加到 DataGrid:

private ...second_Click(object sender, ...)
{
    //add the columns to dt_main...

    DataGrid1.ItemsSource = null;
    DataGrid1.ItemsSource = dt_main.DefaultView;
}