【问题标题】:How to add columns to a DataGrid?如何将列添加到 DataGrid?
【发布时间】:2021-10-20 09:12:23
【问题描述】:

我以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(这是用于填写表格列表)然后点击second_click(这是用于选择表格),但是虽然填写了DataTable的Columns属性,但我什么也没看到在我的 DataGrid 中,您可以在以下屏幕截图中看到(DataGrid 由红色箭头显示):

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

【问题讨论】:

  • DataGrid1.ItemsSource= dt_main.DefaultView 怎么样;
  • @ziakhan:这意味着DataGrid1.ItemsSourceDataGrid1.DataContext 需要等于dt_main.DefaultView?看起来很奇怪。不过我试过了,但并没有解决问题。

标签: c# wpf datatable datagrid


【解决方案1】:

只有在实际设置了ItemsSource 属性时才会自动生成这些列。

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

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

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

【讨论】:

  • 你是个巫师!因此,DataGrid 失去了与它的ItemsSource 的连接,必须首先将其设置为null,然后再设置为正确的值才能使其正常工作。 (我从来没有想过)
猜你喜欢
  • 2015-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多