3

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.

user3496167
  • 165
  • 4
  • 11

1 Answers1

3

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:

Community
  • 1
  • 1
McGarnagle
  • 101,349
  • 31
  • 229
  • 260
  • Thanks a lot. The second solution is exactly what I am looking for. – user3496167 Apr 26 '14 at 01:12
  • How to check if there are event listeners on the datagridview? if there are non, whould that `dataGrid.Loaded -= DataGridLoaded;` give an error? – TiyebM Jun 16 '20 at 12:59