1

我在 WPF 中有一个 DataGrid(一个扩展 DataGrid 的类),我想编辑其中的项目。但当然我收到以下错误:

Operation is not valid while ItemsSource is in use. 
Access and modify elements with ItemsControl.ItemsSource instead.

我尝试更改 DataGrid 的 itemsSource,然后添加项目,但仍然出现相同的错误。就像是:

public class MyDG:DataGrid{

    public void add(){
        List<TimesheetRecord> records = new List<TimesheetRecord>();

        foreach(TimesheetRecord rec in this.Items){
            records.Add(rec);
        }

        //DO SOME STUFF, ADD MORE ITEMS TO records

        ItemCollection col = this.Items;
        this.ItemsSource = records;
        col.Clear();

       foreach(TimesheetRecord rec in records){
            col.add(red);//exception thrown here
        }

        this.ItemsSource = col;
    }

}

当我已经将 itemsSource 更改为不同的列表时,我不明白为什么会出现该错误...?

我不能(轻松)将项目添加到最初绑定为 itemsSource 的列表中,因为该列表存在于不同的类中。我最好在 MyDG 类中有一个全局变量,List<TimesheetRecord> myItems = new List<TimesheetRecord>();然后在 MyDG go 的构造函数中this.ItemsSource = myItems

或者你有任何其他建议我应该如何去做?我对任何事情都持开放态度,因为这是我第一次使用数据绑定,所以我可能做错了什么......

4

3 回答 3

4

Decalre 记录集合为:

ObservableCollection<TimesheetRecord> records = new ObservableCollection<TimesheetRecord>();

并将其数据绑定到 DataGrid。根据需要操作记录集合,数据绑定将负责保持 UI 与集合同步。

于 2012-08-13T17:42:25.643 回答
2

您必须选择是否使用ItemsItemsSource,您不能同时使用两者。在使用ItemsSource时尝试修改Items会假定不支持的隐式转换,因此会出现错误。

在这种情况下,似乎最好的方法可能是设置Items并直接添加到该集合中。要使用ItemsSource,您需要完全按照您所写的那样,将对ItemsSource集合 ( List<TimesheetRecord> ) 的引用传递给您的DataGrid类。

于 2012-08-13T17:44:43.453 回答
1

将“记录”分配给 ItemsSource 后,您就已经更新了您的收藏。无需手动将项目添加到 dataGrid.Items 集合。

于 2012-08-13T17:42:12.033 回答