当我在列表中搜索时,我将结果传递给函数以加载DataGrid 每次触发AutoGeneratingColumn事件时,它都会再次重复相同的列。 启动应用程序时,事件会检查列一次,执行第一次搜索检查两次,第二次检查三次,依此类推。 我有下一个加载DataGrid的函数:
private void cargarListaAgenda(List<listaAgendaClass> lista)
{
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
{
gridAgendaDataGridAgenda.AutoGeneratingColumn += (s, e) =>
{
e.Column.Visibility = Visibility.Hidden;
if (e.Column.Header.ToString() == "Nombre" || e.Column.Header.ToString() == "Alias" || e.Column.Header.ToString() == "Apellidos")
{
e.Column.Visibility = Visibility.Visible;
if (e.Column.Header.ToString() != "Apellidos")
e.Column.Width = new DataGridLength(gridAgendaDataGridAgenda.Width * 0.33);
else
e.Column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
}
};
gridAgendaDataGridAgenda.ItemsSource = null;
gridAgendaDataGridAgenda.ItemsSource = lista;
}));
}
答案 0 :(得分:0)
每次调用cargarListaAgenda
方法时,似乎都附加了一个新的事件处理程序。
尝试在添加新事件之前删除事件处理程序:
private void cargarListaAgenda(List<listaAgendaClass> lista)
{
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
{
gridAgendaDataGridAgenda.AutoGeneratingColumn -= GridAgendaDataGridAgenda_AutoGeneratingColumn;
gridAgendaDataGridAgenda.AutoGeneratingColumn += GridAgendaDataGridAgenda_AutoGeneratingColumn;
gridAgendaDataGridAgenda.ItemsSource = lista;
}));
}
private void GridAgendaDataGridAgenda_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
e.Column.Visibility = Visibility.Hidden;
if (e.Column.Header.ToString() == "Nombre" || e.Column.Header.ToString() == "Alias" || e.Column.Header.ToString() == "Apellidos")
{
e.Column.Visibility = Visibility.Visible;
if (e.Column.Header.ToString() != "Apellidos")
e.Column.Width = new DataGridLength(gridAgendaDataGridAgenda.Width * 0.33);
else
e.Column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
}
}