更改 DataTable 行值后更新 DataGrid

Updating DataGrid after changing DataTable row value

我有一个 DataGrid(名为 m_grid)设置,以便它显示 DataTable 的行:

 <DataGrid name="m_grid">
      <DataGrid.Columns>
           <DataGridCheckBoxColumn Header="Locked"
                                   Binding="{Binding '[Locked]'}"/>
           ...
      </DataGrid.Columns>
 </DataGrid>

我在后面的代码中填充网格是这样的:

 DataTable l_table = Database.GetTable("SELECT * FROM Reports")
 m_grid.ItemsSource = l_table.Rows;

我有一个上下文菜单,其点击事件附加了以下方法:

 DataRow l_row = m_grid.SelectedItem as DataRow;
 int l_id = (int)l_row["Report ID"];
 int l_result = Database.Execute("Update [Reports] SET [Locked] = not [Locked] WHERE [Report ID]=" + l_id;
 if (l_result > 0){
      l_row["Locked"] = !l_row["Locked"];
 }

点击后运行,数据库更新,行中的值发生了变化,但DataGrid保持不变。我尝试使用

m_grid.BeginEdit();
// execute code
m_grid.CommitEdit();

但这没有任何效果。我是不是在这里遗漏了什么,或者我是否需要更改将数据绑定到网格的方式。谢谢

我认为 DataRow 没有实现通知。而不是使用行集合作为 ItemsSource (m_grid.ItemsSource = l_table.Rows;) 使用 DefaultView:

 m_grid.ItemsSource = l_table.DefaultView;

它还会在 DataGrid 中正确地自动生成列。并且DataView支持排序和过滤。

但请注意,在进行此类更改后,DataGrid 将包含类型为 DataRowView 的项(其中包含 Row 属性)。使用 SelectedItem 的代码也应该修改