简体   繁体   中英

Couldn't invoke EventHandler for AutoGeneratedColumns

I have a datagrid in my WPF application and i am binding an Ienumerable collection to the itemsource of the datagrid.

I need to add a handler for AutoGenerated columns in DataGrid after binding it. But i can't.

this.dataGrid1.ItemsSource = ineumerable_collection;
dataGrid1.AutoGeneratedColumns += new EventHandler(dataGrid1_AutoGeneratedColumns);//Not working

I have set Autogeneratecolumns as True in my XAML. But when i run my application it is not invoking the event handler dataGrid1_AutoGeneratedColumns. Thanks in advance if u could solve my problem!

But when i run my application it is not invoking the event handler

You should first subscribe to the event:

dataGrid1.AutoGeneratedColumns += dataGrid1_AutoGeneratedColumns

and then change items source:

this.dataGrid1.ItemsSource = ineumerable_collection;

because this event raised after ItemsSource changed and the last column was generated.

According to MSDN:

The AutoGeneratedColumns event is raised every time the DataGrid attempts to generate columns.For example, AutoGeneratedColumns is raised when the DataGrid is initialized, AutoGenerateColumns is set to true, or the ItemsSource is changed, even if the ItemsSource is null.

Try to subscribe on an event before setting ItemsSource.

The problem is that you're attaching the event handler after you've changed the ItemsSource , which means the columns get generated before your handler is attached. Just switch the order of the two statements.

dataGrid1.AutoGeneratedColumns += new EventHandler(dataGrid1_AutoGeneratedColumns);
this.dataGrid1.ItemsSource = ineumerable_collection;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM