Reputation: 175
I'm trying to dynamically load columns when DataGrid
is loaded, and add the event handler with some parameters in initialization.
dataGrid.Loaded += (sender, args) => AddColumns(dataGrid, GetAttachedColumns(dataGrid));
But have no idea to how to remove this handler after DataGrid is loaded. The following code doesn't work.
dataGrid.Loaded -= (sender, args) => AddColumns(dataGrid, GetAttachedColumns(dataGrid));
Please help out. Thanks.
Upvotes: 3
Views: 1008
Reputation: 102793
In cases when you need to explicitly remove the event listener, you can't really use an anonymous handler. Try a plain old method:
private void DataGridLoaded(object sender, RoutedEventArgs args)
{
AddColumns(dataGrid, GetAttachedColumns(dataGrid));
}
Which you can then simply add/remove:
dataGrid.Loaded += DataGridLoaded;
dataGrid.Loaded -= DataGridLoaded;
Alternatively, if you really wanted to use the lambda form, you could hold onto a reference in a member variable. Eg:
public class MyControl
{
private RoutedEventHandler _handler;
public void Subscribe()
{
_handler = (sender, args) => AddColumns(dataGrid, GetAttachedColumns(dataGrid));
dataGrid.Loaded -= _handler;
}
public void Unsubscribe()
{
dataGrid.Loaded -= _handler;
}
}
See also other questions:
Upvotes: 3