Question

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.

Was it helpful?

Solution

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:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top