如何删除动态创建的事件处理程序



我是相对较新的。我认为我遇到的问题很简单,但我找不到解决方案。单击 button1 将打开一个弹出窗口,并添加到canvas1 MouseDown 事件处理程序canvas1.MouseDown += (s1, e1) =>{...}; 我想在用户关闭弹出窗口时将其删除。这是整个代码:

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) =>
            {
                Popup popup = new Popup();
                popup.PlacementTarget = button1;
                popup.IsOpen = true;
                Button closePopupButton = new Button();
                closePopupButton.Content = "close";
                closePopupButton.Click += (s1, e1) =>
                {
                    popup.IsOpen = false;
                    // remove canvas1.MouseDown event handler here
                };
                popup.Child = closePopupButton;
                canvas1.MouseDown += (s1, e1) =>
                {
                    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);
        }
    }
}

事件处理程序保存在变量中的某个位置

MouseButtonEventHandler onMousedown = (o, args) => 
{ 
    ...
};
canvas1.MouseDown += onMouseDown;

稍后您可以再次删除事件处理程序:

canvas1.MouseDown -= onMouseDown;

相关内容

  • 没有找到相关文章

最新更新