Reputation: 1113
I've seen this in many answers, and I can't figure out how it works.
It usually goes this way (pseudocode):
UIElement.AddHandler(routedEvent, new EventHandler(handler));
which basically seems to creates a new instance of a delegate and pass it so that it is added to a list of delegates. So far, so good.
But then, to remove it, you do:
UIElement.RemoveHandler(routedEvent, new EventHandler(handler));
Which just seems to remove a new instance, not the previous one.
What's going on, here?
Upvotes: 6
Views: 2075
Reputation: 169300
You can't pass a reference to a new EventHandler
that you don't keep any reference to if you want to be able to remove it later on.
Cast the handler to the appropriate delegate type.
This works, i.e. the event handler is only invoked once when the Button
is clicked:
Code:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
btn.AddHandler(Button.ClickEvent, (RoutedEventHandler)OnClick);
}
private void OnClick(object sender, RoutedEventArgs e)
{
MessageBox.Show("click");
btn.RemoveHandler(Button.ClickEvent, (RoutedEventHandler)OnClick);
}
}
XAML:
<Button x:Name="btn" Content="Button" />
Upvotes: 6