简体   繁体   English

加载后如何更新DataGrid?

[英]How do I update a DataGrid after it has already been loaded?

在此处输入图片说明

The above shows my DataGrid.dataGrid_Loaded() method creating a couple of "records" and adding them to a list that my DataGrid uses a its "ItemsSource" 上面显示了我的DataGrid.dataGrid_Loaded()方法,创建了几个“记录”,并将它们添加到我的DataGrid使用其“ ItemsSource”的列表中

On line 156 I have another record commented out (which is after the grid.ItemsSource was set). 在第156行上,我有另一条记录被注释掉了(在grid.ItemsSource设置之后)。 If I add that line back in, my code breaks. 如果我重新添加该行,我的代码将中断。 There must be a way to update my DataGrid with new data, but how? 必须有一种方法可以用新数据更新我的DataGrid,但是如何?

Thank you for your help! 谢谢您的帮助!

When I uncomment line 156, I get: 当我取消注释第156行时,我得到:

An unhandled exception of type 'System.InvalidOperationException' occurred in PresentationFramework.dll PresentationFramework.dll中发生了类型为'System.InvalidOperationException'的未处理异常

Additional information: An ItemsControl is inconsistent with its items source. 附加信息:一个ItemsControl与其项目源不一致。

See the inner exception for more information. 有关更多信息,请参见内部异常。

You need to clear ItemsSource before changing it: 您需要在更改之前清除ItemsSource

List<string> items = new List<string>() { "a", "b" };
dataGrid.ItemsSource = items;

// some code

dataGrid.ItemsSource = null;
items.Add("c");
dataGrid.ItemsSource = items;

// dataGrid contains: "a", "b", "c"

You may want to use ObservableCollection<T> and use binding in your XAML - items will update automatically. 您可能要使用ObservableCollection<T>并在XAML中使用绑定-项目将自动更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM