我有MVVM Applikation。现在我需要一个具有可变数量的列和行的Datagrid。 初始填充datagrid工作正常,但是在使用以下异常更新datagrid时应用程序会随机崩溃
“UI中出现未处理的异常:'收集已修改;枚举操作>可能无法执行。'。”
在调用drawDatagrid()
之后,崩溃直接发生我的xaml中的代码:
<DataGrid
MaxWidth="{Binding Width}"
ItemsSource="{Binding SizeQuantityTable}"
AutoGenerateColumns="True"
SelectionMode="Single" SelectionUnit="CellOrRowHeader"
MouseDown="DataGrid1_MouseClick"
MouseDoubleClick="AppointmentOnMouseDoubleClick"
CanUserResizeColumns="False"
CanUserResizeRows="False"
CanUserSortColumns="False"
CanUserAddRows="False"
CanUserDeleteRows="False"
CanUserReorderColumns="False"
ScrollViewer.CanContentScroll="True"
HorizontalAlignment="Left"
VerticalGridLinesBrush="DarkGray"
GridLinesVisibility="All"
HorizontalGridLinesBrush="DarkGray"
/>
ViewModel中用于更新Datagrid的代码
private void drawDataGrid()
{
SizeQuantityTable = new DataTable();
DataColumn dayColumn = new DataColumn();
try
{
dayColumn.ColumnName = "Tag";
SizeQuantityTable.Columns.Add(dayColumn);
foreach (var line in CalenderWorkPlanLines)
{
DataColumn column = new DataColumn();
column.ColumnName = line.Fullname;
SizeQuantityTable.Columns.Add(column);
}
for (int i = 0; i < DaysOfMonth.Count(); i++)
{
DataRow row = SizeQuantityTable.NewRow();
row[dayColumn] = DaysOfMonth[i];
int j = 1;
foreach (var line in CalenderWorkPlanLines)
{
var tmp = line.AppointmentsString.ToList();
row[SizeQuantityTable.Columns[j]] = line.AppointmentsString[i];
j++;
}
SizeQuantityTable.Rows.Add(row);
}
App.Current.Dispatcher.BeginInvoke(
(System.Action)(() =>
{
RaisePropertyChanged("SizeQuantityTable");
}), null);
}
catch (Exception ex)
{
Loggers.StartUI.Error("Exception during population of SizeQuantityTable - WorkPlanAppointments" + "in CalenderWorkplanViewModel", ex);
}
}
答案 0 :(得分:0)
虽然我在drawDataGrid
方法中看不到任何明显的编码错误,但您提到的Exception
是由于您无法修改使用{{枚举的集合中的项目而导致的1}} class,这是在Enumerator
循环中使用的。
修复很简单...一旦找到了试图修改项目的foreach
循环,就可以简单地用foreach
循环替换foreach
循环。这是一个简短的例子:
for
使用下面的代码代替上面的代码:
foreach (Person person in People)
{
person = anotherPerson; // not allowed
}