我有 MVVM 应用程序。现在我需要一个具有可变数量的列和行的 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);
}
}