我比较新手。我认为问题很简单,但我找不到解决办法。单击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);
}
}
}
答案 0 :(得分:4)
将eventhandler保存在变量
中MouseButtonEventHandler onMousedown = (o, args) =>
{
...
};
canvas1.MouseDown += onMouseDown;
稍后您可以再次删除事件处理程序:
canvas1.MouseDown -= onMouseDown;