Search code examples
c#wpfattachedbehaviors

Event unsubscription via anonymous delegate


I am using Resharper 5.1 code analysis many a times i get a comment from resharper as

"Event unsubscription via anonymous delegate"

#Part of Code  

if (((bool)e.NewValue))
{
    listView.PreviewTextInput += (o,args) =>
        listView_PreviewTextInput(o,args,listView);
}
else
{
    listView.PreviewTextInput -= (o, args) => 
        listView_PreviewTextInput(o, args, listView);
}

How could i correct or optimze this thing


Solution

  • You can extract the lamdba to a variable:

    EventHandler func = (sender, e) =>
        listView_PreviewTextInput(sender, e, listView);
    
    if (((bool)e.NewValue))
    {
        listView.PreviewTextInput += func;
    }
    else
    {
        listView.PreviewTextInput -= func;
    }