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
または、これを行うにはどうすればよいか、他に何か提案はありますか? データバインディングを使用したのはこれが初めてなので、私は何に対してもオープンです。おそらく何か間違ったことをしているのでしょう...