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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12707423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 05:37:23  来源:igfitidea点击:

How to remove event handler which is dynamically created?

c#wpfevent-handling

提问by butaro

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 canvas1a MouseDown event handler canvas1.MouseDown += (s1, e1) =>{...};I want to remove this when the user closes the popup. Here's the whole code:

我是比较新手。我的问题是我认为的一个简单问题,但我找不到解决方案。单击 button1 会打开一个弹出窗口并添加到canvas1MouseDown 事件处理程序中,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);
        }
    }
}

回答by doerig

save the eventhandler somewhere in a variable

将事件处理程序保存在变量中的某处

MouseButtonEventHandler onMousedown = (o, args) => 
{ 
    ...
};

canvas1.MouseDown += onMouseDown;

and later you can remove the eventhandler again:

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

canvas1.MouseDown -= onMouseDown;