title: How to remove event handler which is dynamically created?
body: <p>I am relatively newbie. The problem I have is a simple one I think, but I cant find a solution. Clicking on button1 opens a popup and adds to <code>canvas1</code> a MouseDown event handler <code>canvas1.MouseDown += (s1, e1) =&gt;{...};</code> I want to remove this when the user closes the popup. Here's the whole code:</p>
  
  <pre><code>namespace MyfApplication1
  {
      public partial class MainWindow : Window
      {
          public MainWindow()
          {
              InitializeComponent();
  
              int linesNumber = 0;
  
              Button button1 = new Button();
              button1.Content = "Draw";
              button1.HorizontalAlignment = HorizontalAlignment.Left;
              button1.VerticalAlignment = VerticalAlignment.Top;
              button1.Click += (s, e) =&gt;
              {
                  Popup popup = new Popup();
                  popup.PlacementTarget = button1;
                  popup.IsOpen = true;
  
                  Button closePopupButton = new Button();
                  closePopupButton.Content = "close";
                  closePopupButton.Click += (s1, e1) =&gt;
                  {
                      popup.IsOpen = false;
                      // remove canvas1.MouseDown event handler here
                  };
                  popup.Child = closePopupButton;
  
                  canvas1.MouseDown += (s1, e1) =&gt;
                  {
                      Point point = Mouse.GetPosition(canvas1);
                      Line line = new Line();
                      line.X2 = point.X; line.Y2 = point.Y;
                      line.Stroke = Brushes.Red; line.StrokeThickness = 1;
                      canvas1.Children.Add(line);
                      linesNumber++;
                  };
              };
              grid1.Children.Add(button1);
          }
      }
  }
  </code></pre>