[英]How to remove event handler which is dynamically created?
我是新手。 我認為這個問題很簡單,但是找不到解決方案。 單擊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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.