为 PathFigure C# WPF 动态添加事件处理程序 (MouseDown)

Add event handler (MouseDown) dynamically for PathFigure C# WPF

我用这段代码动态地从点创建了一个对象:

SolidColorBrush brushColor = (SolidColorBrush)new BrushConverter().ConvertFromString(_brushColor);

PathFigure figures = new PathFigure();
figures.StartPoint = points[0];
points.RemoveAt(0);
figures.Segments = new PathSegmentCollection(points.Select((p, i) => new LineSegment(p, i % 2 == 0)));
PathGeometry pg = new PathGeometry();
pg.Figures.Add(figures);
canvas.Children.Add(new Path { Stroke = brushColor, StrokeThickness = 3, Data = pg });

现在我想为此对象添加事件处理程序。如果对象是路径或折线类型,则不会有问题。我会像这样添加事件处理程序:

poly.MouseDown += new MouseButtonEventHandler(poly_MouseDown);

void poly_MouseDown(object sender, MouseButtonEventArgs e)
{
     //code
}

问题是我必须使用不接受 MouseDown 事件处理程序的 Figures 和 PathGeometry。因为它们来自 System.Windows.Media class 而 Path/Polyline 来自 System.Windows.Shapes 我找不到将正确的事件处理程序 (MouseDown) 分配给我的 Figure 对象的解决方案。

解决方案是什么,或者是否有解决此问题的好方法?也许以某种方式投射或转换它?

据我所知,您正在跳过关键的一步。 先声明 Path 对象,给它事件,然后将它插入到你的 Canvas:

SolidColorBrush brushColor = (SolidColorBrush)new BrushConverter ().ConvertFromString (_brushColor);

PathFigure figures = new PathFigure ();
figures.StartPoint = points[0];
points.RemoveAt (0);
figures.Segments = new PathSegmentCollection (points.Select ((p, i) => new LineSegment (p, i % 2 == 0)));
PathGeometry pg = new PathGeometry ();
pg.Figures.Add (figures);
Path pgObject = new Path({ Stroke = brushColor, StrokeThickness = 3, Data = pg });
pgObject.MouseDown+=new MouseButtonEventHandler(poly_MouseDown);
canvas.Children.Add (pgObject);